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 |
|---|---|---|---|---|---|
abriasffxi/darkstar | scripts/globals/weaponskills/metatron_torment.lua | 19 | 2291 | -----------------------------------
-- 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/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 = 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.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
local amDuration = 20 * math.floor(tp/1000);
player:addStatusEffect(EFFECT_AFTERMATH, -21, 0, amDuration, 0, 5);
target:addStatusEffect(EFFECT_DEFENSE_DOWN, 19, 0, 120);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
abriasffxi/darkstar | scripts/globals/bcnm.lua | 1 | 42794 | require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
-- NEW SYSTEM BCNM NOTES
-- The "core" functions TradeBCNM EventUpdateBCNM EventTriggerBCNM EventFinishBCNM all return TRUE if the action performed is covered by the function.
-- This means all the old code will still be executed if the new functions don't support it. This means that there is effectively 'backwards compatibility' with the old system.
-- array to map (for each zone) the item id of the valid trade item with the bcnmid in the database
-- e.g. zone, {itemid, bcnmid, itemid, bcnmid, itemid, bcnmid}
-- DO NOT INCLUDE MAAT FIGHTS
itemid_bcnmid_map = {6, {0, 0}, -- Bearclaw_Pinnacle
8, {0, 0}, -- Boneyard_Gully
10, {0, 0}, -- The_Shrouded_Maw
13, {0, 0}, -- Mine_Shaft_2716
17, {0, 0}, -- Spire of Holla
19, {0, 0}, -- Spire of Dem
21, {0, 0}, -- Spire of Mea
23, {0, 0}, -- Spire of Vahzl
29, {0, 0}, -- Riverne Site #B01
31, {0, 0}, -- Monarch Linn
32, {0, 0}, -- Sealion's Den
35, {0, 0}, -- The Garden of RuHmet
36, {0, 0}, -- Empyreal Paradox
139, {1177, 4, 1552, 10, 1553, 11, 1131, 12, 1175, 15, 1180, 17}, -- Horlais Peak
140, {1551, 34, 1552, 35, 1552, 36}, -- Ghelsba Outpost
144, {1166, 68, 1178, 81, 1553, 76, 1180, 82, 1130, 79, 1552, 73}, -- Waughroon Shrine
146, {1553, 107, 1551, 105, 1177, 100}, -- Balgas Dias
163, {1130, 129, 1130, 130}, -- Sacrificial Chamber
168, {0, 0}, -- Chamber of Oracles
170, {0, 0}, -- Full Moon Fountain
180, {1550, 293}, -- LaLoff Amphitheater
181, {0, 0}, -- The Celestial Nexus
201, {1546, 418, 1174, 417}, -- Cloister of Gales
202, {1548, 450, 1172, 449}, -- Cloister of Storms
203, {1545, 482, 1171, 481}, -- Cloister of Frost
206, {0, 0}, -- Qu'Bia Arena
207, {1544, 545}, -- Cloister of Flames
209, {1547, 578, 1169, 577}, -- Cloister of Tremors
211, {1549, 609}}; -- Cloister of Tides
-- array to map (for each zone) the BCNM ID to the Event Parameter corresponding to this ID.
-- DO NOT INCLUDE MAAT FIGHTS (only included one for testing!)
-- bcnmid, paramid, bcnmid, paramid, etc
-- The BCNMID is found via the database.
-- The paramid is a bitmask which you need to find out. Being a bitmask, it will be one of:
-- 0, 1, 2, 3, 4, 5, ...
bcnmid_param_map = {6, {640, 0, 643, 3},
8, {672, 0, 673, 1},
10, {704, 0, 706, 2},
13, {736, 0},
17, {768, 0},
19, {800, 0},
21, {832, 0},
23, {864, 0},
29, {896, 0},
31, {960, 0, 961, 1},
32, {992, 0, 993, 1},
35, {1024, 0},
36, {1056, 0},
139, {0, 0, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 10, 10, 11, 11, 12, 12, 15, 15, 17, 17},
140, {32, 0, 33, 1, 34, 2, 35, 3, 36, 4},
144, {65, 1, 73, 9, 64, 0, 67, 3, 68, 4, 70, 6, 71, 7, 72, 8, 81, 17, 76, 12, 82, 18, 79, 15},
146, {99, 3, 96, 0, 101, 5, 102, 6, 103, 7, 107, 11, 105, 9},
163, {128, 0, 129, 1, 130, 2},
165, {160, 0, 161, 1},
168, {192, 0, 194, 2, 195, 3, 196, 4},
170, {224, 0, 225, 1},
179, {256, 0},
180, {293, 5, 288, 0, 289, 1, 290, 2, 291, 3, 292, 4},
181, {320, 0},
201, {416, 0, 417, 1, 418, 2, 420, 4},
202, {448, 0, 449, 1, 450, 2, 452, 4},
203, {480, 0, 481, 1, 482, 2, 484, 4},
206, {512, 0, 516, 4, 517, 5, 518, 6, 519, 7, 532, 20},
207, {544, 0, 545, 1, 547, 3},
209, {576, 0, 577, 1, 578, 2, 580, 4},
211, {608, 0, 609, 1, 611, 3}};
-- Call this onTrade for burning circles
function TradeBCNM(player, zone, trade, npc)
-- return false;
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then -- cant start a new bc
player:messageBasic(94, 0, 0);
return false;
elseif (player:hasWornItem(trade:getItemId())) then -- If already used orb or testimony
player:messageBasic(56, 0, 0); -- i need correct dialog
return false;
end
if (CheckMaatFights(player, zone, trade, npc)) then -- This function returns true for maat fights
return true;
end
-- the following is for orb battles, etc
local id = ItemToBCNMID(player, zone, trade);
if (id == -1) then -- no valid BCNMs with this item
-- todo: display message based on zone text offset
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
return false;
else -- a valid BCNM with this item, start it.
mask = GetBattleBitmask(id, zone, 1);
if (mask == -1) then -- Cannot resolve this BCNMID to an event number, edit bcnmid_param_map!
print("Item is for a valid BCNM but cannot find the event parameter to display to client.");
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
return false;
end
if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances
print("all bcnm instances are currently occupied.");
npc:messageBasic(246, 0, 0); -- this wont look right in other languages!
return true;
end
player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0);
return true;
end
end;
function EventTriggerBCNM(player, npc)
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then
if (player:isInBcnm() == 1) then
player:startEvent(0x7d03); -- Run Away or Stay menu
else -- You're not in the BCNM but you have the Battlefield effect. Think: non-trader in a party
status = player:getStatusEffect(EFFECT_BATTLEFIELD);
playerbcnmid = status:getPower();
playermask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 1);
if (playermask~=-1) then
-- This gives players who did not trade to go in the option of entering the fight
player:startEvent(0x7d00, 0, 0, 0, playermask, 0, 0, 0, 0);
else
player:messageBasic(94, 0, 0);
end
end
return true;
else
if (checkNonTradeBCNM(player, npc)) then
return true;
end
end
return false;
end;
function EventUpdateBCNM(player, csid, option, entrance)
-- return false;
local id = player:getVar("trade_bcnmid"); -- this is 0 if the bcnm isnt handled by new functions
local skip = CutsceneSkip(player, npc);
print("UPDATE csid "..csid.." option "..option);
-- seen: option 2, 3, 0 in that order
if (csid == 0x7d03 and option == 2) then -- leaving a BCNM the player is currently in.
player:bcnmLeave(1);
return true;
end
if (option == 255 and csid == 0x7d00) then -- Clicked yes, try to register bcnmid
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then
-- You're entering a bcnm but you already had the battlefield effect, so you want to go to the
-- instance that your battlefield effect represents.
player:setVar("bcnm_instanceid_tick", 0);
player:setVar("bcnm_instanceid", player:getBattlefieldID()); -- returns 255 if non-existent.
return true;
end
inst = player:bcnmRegister(id);
if (inst > 0) then
player:setVar("bcnm_instanceid", inst);
player:setVar("bcnm_instanceid_tick", 0);
player:updateEvent(0, 3, 0, 0, 1, 0);
if (entrance ~= nil and player:getBattlefield() ~= nil) then
player:getBattlefield():setEntrance(entrance);
end
-- player:tradeComplete();
else
-- no free battlefields at the moment!
print("no free instances");
player:setVar("bcnm_instanceid", 255);
player:setVar("bcnm_instanceid_tick", 0);
end
elseif (option == 0 and csid == 0x7d00) then -- Requesting an Instance
-- Increment the instance ticker.
-- The client will send a total of THREE EventUpdate packets for each one of the free instances.
-- If the first instance is free, it should respond to the first packet
-- If the second instance is free, it should respond to the second packet, etc
local instance = player:getVar("bcnm_instanceid_tick");
instance = instance + 1;
player:setVar("bcnm_instanceid_tick", instance);
if (instance == player:getVar("bcnm_instanceid")) then
-- respond to this packet
local mask = GetBattleBitmask(id, player:getZoneID(), 2);
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
local playerbcnmid = status:getPower();
if (mask < playerbcnmid) then
mask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 2);
player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS
player:bcnmEnter(id);
player:setVar("bcnm_instanceid_tick", 0);
-- print("mask is "..mask)
-- print("playerbcnmid is "..playerbcnmid);
elseif (mask >= playerbcnmid) then
mask = GetBattleBitmask(id, player:getZoneID(), 2);
player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS
player:bcnmEnter(id);
player:setVar("bcnm_instanceid_tick", 0);
-- print("mask2 is "..mask)
-- print("playerbcnmid2 is "..playerbcnmid);
end
if (entrance ~= nil and player:getBattlefield() ~= nil) then
player:getBattlefield():setEntrance(entrance);
end
elseif (player:getVar("bcnm_instanceid") == 255) then -- none free
-- print("nfa");
-- player:updateEvent(2, 5, 0, 0, 1, 0); -- @cs 32000 0 0 0 0 0 0 0 2
-- param1
-- 2=generic enter cs
-- 3=spam increment instance requests
-- 4=cleared to enter but cant while ppl engaged
-- 5=dont meet req, access denied.
-- 6=room max cap
-- param2 alters the eventfinish option (offset)
-- param7/8 = does nothing??
end
-- @pos -517 159 -209
-- @pos -316 112 -103
-- player:updateEvent(msgid, bcnmFight, 0, record, numadventurers, skip); skip=1 to skip anim
-- msgid 1=wait a little longer, 2=enters
end
return true;
end;
function EventFinishBCNM(player, csid, option)
print("FINISH csid "..csid.." option "..option);
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then -- Temp condition for normal bcnm (started with onTrigger)
return false;
else
local id = player:getVar("trade_bcnmid");
local item = player:getVar("trade_itemid");
if (id == 68 or id == 418 or id == 450 or id == 482 or id == 545 or id == 578 or id == 609 or id == 293) then
player:tradeComplete(); -- Removes the item
elseif ((item >= 1426 and item <= 1440) or item == 1130 or item == 1131 or item == 1175 or item == 1177 or item == 1180 or item == 1178 or item == 1551 or item == 1552 or item == 1553) then -- Orb and Testimony (one time item)
player:createWornItem(item);
end
return true;
end
end;
-- Returns TRUE if you're trying to do a maat fight, regardless of outcome e.g. if you trade testimony on wrong job, this will return true in order to prevent further execution of TradeBCNM. Returns FALSE if you're not doing a maat fight (in other words, not trading a testimony!!)
function CheckMaatFights(player, zone, trade, npc)
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
-- check for maat fights (one maat fight per zone in the db, but >1 mask entries depending on job, so we
-- need to choose the right one depending on the players job, and make sure the right testimony is traded,
-- and make sure the level is right!
local itemid = trade:getItemId();
local job = player:getMainJob();
local lvl = player:getMainLvl();
if (itemid >= 1426 and itemid <= 1440) then -- The traded item IS A TESTIMONY
if (lvl < 66) then
return true;
end
if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances
print("all bcnm instances are currently occupied.");
npc:messageBasic(246, 0, 0);
return true;
end
-- Zone, {item, job, menu, bcnmid, ...}
maatList = {139, {1426, 1, 32, 5, 1429, 4, 64, 6, 1436, 11, 128, 7}, -- Horlais Peak [WAR BLM RNG]
144, {1430, 5, 64, 70, 1431, 6, 128, 71, 1434, 9, 256, 72}, -- Waughroon Shrine [RDM THF BST]
146, {1427, 2, 32, 101, 1428, 3, 64, 102, 1440, 15, 128, 103}, -- Balga's Dais [MNK WHM SMN]
168, {1437, 12, 4, 194, 1438, 13, 8, 195, 1439, 14, 16, 196}, -- Chamber of Oracles [SAM NIN DRG]
206, {1432, 7, 32, 517, 1433, 8, 64, 518, 1435, 10, 128, 519} };-- Qu'Bia Arena [PLD DRK BRD]
for nb = 1, #maatList, 2 do
if (maatList[nb] == zone) then
for nbi = 1, #maatList[nb + 1], 4 do
if (itemid == maatList[nb + 1][nbi] and job == maatList[nb + 1][nbi + 1]) then
player:startEvent(0x7d00, 0, 0, 0, maatList[nb + 1][nbi + 2], 0, 0, 0, 0);
player:setVar("trade_bcnmid", maatList[nb + 1][nbi + 3]);
player:setVar("trade_itemid", maatList[nb + 1][nbi]);
break;
end
end
end
end
return true;
end
-- if it got this far then its not a testimony
return false;
end;
function GetBattleBitmask(id, zone, mode)
-- normal sweep for NON MAAT FIGHTS
local ret = -1;
local mask = 0;
for zoneindex = 1, #bcnmid_param_map, 2 do
if (zone==bcnmid_param_map[zoneindex]) then -- matched zone
for bcnmindex = 1, #bcnmid_param_map[zoneindex + 1], 2 do -- loop bcnms in this zone
if (id==bcnmid_param_map[zoneindex+1][bcnmindex]) then -- found bcnmid
if (mode == 1) then
ret = mask + (2^bcnmid_param_map[zoneindex+1][bcnmindex+1]); -- for trigger (mode 1): 1, 2, 4, 8, 16, 32, ...
else
ret = mask + bcnmid_param_map[zoneindex+1][bcnmindex+1]; -- for update (mode 2): 0, 1, 2, 3, 4, 5, 6, ...
end
end
end
end
end
return ret;
end;
function ItemToBCNMID(player, zone, trade)
for zoneindex = 1, #itemid_bcnmid_map, 2 do
if (zone==itemid_bcnmid_map[zoneindex]) then -- matched zone
for bcnmindex = 1, #itemid_bcnmid_map[zoneindex + 1], 2 do -- loop bcnms in this zone
if (trade:getItemId()==itemid_bcnmid_map[zoneindex+1][bcnmindex]) then
local item = trade:getItemId();
local questTimelineOK = 0;
-- Job/lvl condition for smn battle lvl20
if (item >= 1544 and item <= 1549 and player:getMainJob() == JOBS.SMN and player:getMainLvl() >= 20) then
questTimelineOK = 1;
elseif (item == 1166 and player:getVar("aThiefinNorgCS") == 6) then -- AF3 SAM condition
questTimelineOK = 1;
elseif (item == 1551) then -- BCNM20
questTimelineOK = 1;
elseif (item == 1552) then -- BCNM30
questTimelineOK = 1;
elseif (item == 1131) then -- BCNM40
questTimelineOK = 1;
elseif (item == 1177) then -- BCNM50
questTimelineOK = 1;
elseif (item == 1130) then -- BCNM60
questTimelineOK = 1;
elseif (item == 1175) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1178) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1180) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1553) then -- KSNM99
questTimelineOK = 1;
elseif (item == 1550 and (player:getQuestStatus(OUTLANDS, DIVINE_MIGHT) == QUEST_ACCEPTED or player:getQuestStatus(OUTLANDS, DIVINE_MIGHT_REPEAT) == QUEST_ACCEPTED)) then -- Divine Might
questTimelineOK = 1;
elseif (item == 1169 and player:getVar("ThePuppetMasterProgress") == 2) then -- The Puppet Master
questTimelineOK = 1;
elseif (item == 1171 and player:getVar("ClassReunionProgress") == 5) then -- Class Reunion
questTimelineOK = 1;
elseif (item == 1172 and player:getVar("CarbuncleDebacleProgress") == 3) then -- Carbuncle Debacle (Gremlims)
questTimelineOK = 1;
elseif (item == 1174 and player:getVar("CarbuncleDebacleProgress") == 6) then -- Carbuncle Debacle (Ogmios)
questTimelineOK = 1;
end
if (questTimelineOK == 1) then
player:setVar("trade_bcnmid", itemid_bcnmid_map[zoneindex+1][bcnmindex+1]);
player:setVar("trade_itemid", itemid_bcnmid_map[zoneindex+1][bcnmindex]);
return itemid_bcnmid_map[zoneindex+1][bcnmindex+1];
end
end
end
end
end
return -1;
end;
-- E.g. mission checks go here, you must know the right bcnmid for the mission you want to code.
-- You also need to know the bitmask (event param) which should be put in bcnmid_param_map
function checkNonTradeBCNM(player, npc)
local mask = 0;
local Zone = player:getZoneID();
if (Zone == 6) then -- Bearclaw_Pinnacle
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 6) then -- flames_for_the_dead
mask = GetBattleBitmask(640, Zone, 1);
player:setVar("trade_bcnmid", 640);
elseif (player:hasKeyItem(ZEPHYR_FAN)) then -- Brothers ENM
mask = GetBattleBitmask(643, Zone, 1);
player:setVar("trade_bcnmid", 643);
end
elseif (Zone == 8) then -- Boneyard_Gully
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then -- head_wind
mask = GetBattleBitmask(672, Zone, 1);
player:setVar("trade_bcnmid", 672);
elseif (player:hasKeyItem(MIASMA_FILTER)==true) then
mask = GetBattleBitmask(673, Zone, 1);
player:setVar("trade_bcnmid", 673);
else
end
elseif (Zone == 10) then -- The_Shrouded_Maw
if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then-- DARKNESS_NAMED
mask = GetBattleBitmask(704, Zone, 1);
player:setVar("trade_bcnmid", 704);
elseif (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==true) then -- waking_dreams (diabolos avatar quest)
mask = GetBattleBitmask(706, Zone, 1);
player:setVar("trade_bcnmid", 706);
end
elseif (Zone == 13) then -- Mine_Shaft_2716
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 5) then -- century_of_hardship
mask = GetBattleBitmask(736, Zone, 1);
player:setVar("trade_bcnmid", 736);
end
elseif (Zone == 17) then -- Spire of Holla
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(768, Zone, 1);
player:setVar("trade_bcnmid", 768);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_HOLLA) == false) then -- light of holla
mask = GetBattleBitmask(768, Zone, 1);
player:setVar("trade_bcnmid", 768);
end
elseif (Zone == 19) then -- Spire of Dem
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(800, Zone, 1);
player:setVar("trade_bcnmid", 800);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_DEM) == false) then -- light of dem
mask = GetBattleBitmask(800, Zone, 1);
player:setVar("trade_bcnmid", 800);
end
elseif (Zone == 21) then -- Spire of Mea
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(832, Zone, 1);
player:setVar("trade_bcnmid", 832);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_MEA) == false) then -- light of mea
mask = GetBattleBitmask(832, Zone, 1);
player:setVar("trade_bcnmid", 832);
end
elseif (Zone == 23) then -- Spire of vahzl
if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==8) then -- desires of emptiness
mask = GetBattleBitmask(864, Zone, 1);
player:setVar("trade_bcnmid", 864);
end
elseif (Zone == 29) then -- Riverne Site #B01
if (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar('StormsOfFate') == 2) then -- Storms of Fate BCNM
mask = GetBattleBitmask(896, Zone, 1);
player:setVar("trade_bcnmid", 896);
end
elseif (Zone == 31) then -- Monarch Linn
if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then -- Ancient Vows bcnm
mask = GetBattleBitmask(960, Zone, 1);
player:setVar("trade_bcnmid", 960);
elseif (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 1) then
mask = GetBattleBitmask(961, Zone, 1);
player:setVar("trade_bcnmid", 961);
end
elseif (Zone == 32) then -- Sealion's Den
if (player:getCurrentMission(COP) == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==2) then -- one_to_be_feared
mask = GetBattleBitmask(992, Zone, 1);
player:setVar("trade_bcnmid", 992);
elseif (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then -- warriors_path
mask = GetBattleBitmask(993, Zone, 1);
player:setVar("trade_bcnmid", 993);
end
elseif (Zone == 35) then -- The Garden of RuHmet
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then -- when_angels_fall
mask = GetBattleBitmask(1024, Zone, 1);
player:setVar("trade_bcnmid", 1024);
end
elseif (Zone == 36) then -- Empyreal Paradox
if (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==2) then -- dawn
mask = GetBattleBitmask(1056, Zone, 1);
player:setVar("trade_bcnmid", 1056);
end
elseif (Zone == 139) then -- Horlais Peak
if ((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or
player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") == 9) then -- Mission 2-3
mask = GetBattleBitmask(0, Zone, 1);
player:setVar("trade_bcnmid", 0);
elseif (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") == 2) then
mask = GetBattleBitmask(3, Zone, 1)
player:setVar("trade_bcnmid", 3);
end
elseif (Zone == 140) then -- Ghelsba Outpost
local MissionStatus = player:getVar("MissionStatus");
local sTcCompleted = player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN)
if (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and (sTcCompleted and MissionStatus <= 2 or sTcCompleted == false and MissionStatus == 2)) then -- Sandy Mission 1-3
mask = GetBattleBitmask(32, Zone, 1);
player:setVar("trade_bcnmid", 32);
elseif (player:hasKeyItem(DRAGON_CURSE_REMEDY)) then -- DRG Flag Quest
mask = GetBattleBitmask(33, Zone, 1);
player:setVar("trade_bcnmid", 33);
end
elseif (Zone == 144) then -- Waughroon Shrine
if ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or
player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") == 10) then -- Mission 2-3
mask = GetBattleBitmask(64, Zone, 1);
player:setVar("trade_bcnmid", 64);
elseif ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then
mask = GetBattleBitmask(67, Zone, 1);
player:setVar("trade_bcnmid", 67);
end
elseif (Zone == 146) then -- Balga's Dais
if (player:hasKeyItem(DARK_KEY)) then -- Mission 2-3
mask = GetBattleBitmask(96, Zone, 1);
player:setVar("trade_bcnmid", 96);
elseif ((player:getCurrentMission(WINDURST) == SAINTLY_INVITATION) and (player:getVar("MissionStatus") == 1)) then -- Mission 6-2
mask = GetBattleBitmask(99, Zone, 1);
player:setVar("trade_bcnmid", 99);
end
elseif (Zone == 163) then -- Sacrificial Chamber
if (player:getCurrentMission(ZILART) == THE_TEMPLE_OF_UGGALEPIH) then -- Zilart Mission 4
mask = GetBattleBitmask(128, Zone, 1);
player:setVar("trade_bcnmid", 128);
end
elseif (Zone == 165) then -- Throne Room
if (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") == 3) then -- Mission 5-2
mask = GetBattleBitmask(160, Zone, 1);
player:setVar("trade_bcnmid", 160);
elseif (player:getCurrentMission(BASTOK) == WHERE_TWO_PATHS_CONVERGE and player:getVar("BASTOK92") == 1) then -- bastok 9-2
mask = GetBattleBitmask(161, Zone, 1);
player:setVar("trade_bcnmid", 161);
end
elseif (Zone == 168) then -- Chamber of Oracles
if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES or player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then -- Zilart Mission 6
mask = GetBattleBitmask(192, Zone, 1);
player:setVar("trade_bcnmid", 192);
end
elseif (Zone == 170) then -- Full Moon Fountain
if (player:hasKeyItem(MOON_BAUBLE)) then -- The Moonlit Path
mask = GetBattleBitmask(224, Zone, 1);
player:setVar("trade_bcnmid", 224);
elseif ((player:getCurrentMission(WINDURST) == MOON_READING) and player:getVar("WINDURST92") == 2) then -- Moon reading
mask = GetBattleBitmask(225, Zone, 1);
player:setVar("trade_bcnmid", 225);
end
elseif (Zone == 179) then -- Stellar Fulcrum
if (player:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") == 3) then -- Zilart Mission 8
mask = GetBattleBitmask(256, Zone, 1);
player:setVar("trade_bcnmid", 256);
end
elseif (Zone == 180) then -- La'Loff Amphitheater
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
local qmid = npc:getID();
if (qmid == 17514791 and player:hasKeyItem(SHARD_OF_APATHY) == false) then -- Hume, Ark Angels 1
mask = GetBattleBitmask(288, Zone, 1);
player:setVar("trade_bcnmid", 288);
elseif (qmid == 17514792 and player:hasKeyItem(SHARD_OF_COWARDICE) == false) then -- Tarutaru, Ark Angels 2
mask = GetBattleBitmask(289, Zone, 1);
player:setVar("trade_bcnmid", 289);
elseif (qmid == 17514793 and player:hasKeyItem(SHARD_OF_ENVY) == false) then -- Mithra, Ark Angels 3
mask = GetBattleBitmask(290, Zone, 1);
player:setVar("trade_bcnmid", 290);
elseif (qmid == 17514794 and player:hasKeyItem(SHARD_OF_ARROGANCE) == false) then -- Elvaan, Ark Angels 4
mask = GetBattleBitmask(291, Zone, 1);
player:setVar("trade_bcnmid", 291);
elseif (qmid == 17514795 and player:hasKeyItem(SHARD_OF_RAGE) == false) then -- Galka, Ark Angels 5
mask = GetBattleBitmask(292, Zone, 1);
player:setVar("trade_bcnmid", 292);
end
end
elseif (Zone == 181) then -- The Celestial Nexus
if (player:getCurrentMission(ZILART) == THE_CELESTIAL_NEXUS) then -- Zilart Mission 16
mask = GetBattleBitmask(320, Zone, 1);
player:setVar("trade_bcnmid", 320);
end
elseif (Zone == 201) then -- Cloister of Gales
if (player:hasKeyItem(TUNING_FORK_OF_WIND)) then -- Trial by Wind
mask = GetBattleBitmask(416, Zone, 1);
player:setVar("trade_bcnmid", 416);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_EMERALD_SEAL)) then
mask = GetBattleBitmask(420, Zone, 1);
player:setVar("trade_bcnmid", 420);
end
elseif (Zone == 202) then -- Cloister of Storms
if (player:hasKeyItem(TUNING_FORK_OF_LIGHTNING)) then -- Trial by Lightning
mask = GetBattleBitmask(448, Zone, 1);
player:setVar("trade_bcnmid", 448);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_VIOLET_SEAL)) then
mask = GetBattleBitmask(452, Zone, 1);
player:setVar("trade_bcnmid", 452);
end
elseif (Zone == 203) then -- Cloister of Frost
if (player:hasKeyItem(TUNING_FORK_OF_ICE)) then -- Trial by Ice
mask = GetBattleBitmask(480, Zone, 1);
player:setVar("trade_bcnmid", 480);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AZURE_SEAL)) then
mask = GetBattleBitmask(484, Zone, 1);
player:setVar("trade_bcnmid", 484);
end
elseif (Zone == 206) then -- Qu'Bia Arena
if (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") == 11) then -- Mission 5-1
mask = GetBattleBitmask(512, Zone, 1);
player:setVar("trade_bcnmid", 512);
elseif (player:getCurrentMission(SANDORIA) == THE_HEIR_TO_THE_LIGHT and player:getVar("MissionStatus") == 3) then -- sando 9-2
mask = GetBattleBitmask(516, Zone, 1);
player:setVar("trade_bcnmid", 516);
-- Temp disabled pending BCNM mob fixes
-- elseif (player:getCurrentMission(ACP) >= THOSE_WHO_LURK_IN_SHADOWS_III and player:hasKeyItem(MARK_OF_SEED)) then -- ACP Mission 7
-- mask = GetBattleBitmask(532, Zone, 1);
-- player:setVar("trade_bcnmid", 532);
end
elseif (Zone == 207) then -- Cloister of Flames
if (player:hasKeyItem(TUNING_FORK_OF_FIRE)) then -- Trial by Fire
mask = GetBattleBitmask(544, Zone, 1);
player:setVar("trade_bcnmid", 544);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_SCARLET_SEAL)) then
mask = GetBattleBitmask(547, Zone, 1);
player:setVar("trade_bcnmid", 547);
end
elseif (Zone == 209) then -- Cloister of Tremors
if (player:hasKeyItem(TUNING_FORK_OF_EARTH)) then -- Trial by Earth
mask = GetBattleBitmask(576, Zone, 1);
player:setVar("trade_bcnmid", 576);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AMBER_SEAL)) then
mask = GetBattleBitmask(580, Zone, 1);
player:setVar("trade_bcnmid", 580);
end
elseif (Zone == 211) then -- Cloister of Tides
if (player:hasKeyItem(TUNING_FORK_OF_WATER)) then -- Trial by Water
mask = GetBattleBitmask(608, Zone, 1);
player:setVar("trade_bcnmid", 608);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_CERULEAN_SEAL)) then
mask = GetBattleBitmask(611, Zone, 1);
player:setVar("trade_bcnmid", 611);
end
end
if (mask == -1) then
print("BCNMID/Mask pair not found"); -- something went wrong
return true;
elseif (mask ~= 0) then
player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0);
print("BCNMID found with mask "..mask);
return true;
else
return false;
end
end;
function CutsceneSkip(player, npc)
local skip = 0;
local Zone = player:getZoneID();
if (Zone == 6) then -- Bearclaw Pinnacle
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 6)) then -- flames_for_the_dead
skip = 1;
end
elseif (Zone == 8) then -- Boneyard Gully
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 5)) then -- head_wind
skip = 1;
end
elseif (Zone == 10) then -- The_Shrouded_Maw
if ((player:hasCompletedMission(COP, DARKNESS_NAMED)) or (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") > 2)) then -- DARKNESS_NAMED
skip = 1;
elseif ((player:hasCompleteQuest(WINDURST, WAKING_DREAMS)) or (player:hasKeyItem(WHISPER_OF_DREAMS))) then -- waking_dreams (diabolos avatar quest)
skip = 1;
end
elseif (Zone == 13) then -- Mine Shaft 2716
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") > 5)) then -- century_of_hardship
skip = 1;
end
elseif (Zone == 17) then -- Spire of Holla
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_HOLLA))) then -- light of holla
skip = 1;
end
elseif (Zone == 19) then -- Spire of Dem
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_DEM))) then -- light of dem
skip = 1;
end
elseif (Zone == 21) then -- Spire of Mea
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_MEA))) then -- light of mea
skip = 1;
end
elseif (Zone == 23) then -- Spire of Vahzl
if ((player:hasCompletedMission(COP, DESIRES_OF_EMPTINESS)) or (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8)) then -- desires of emptiness
skip = 1;
end
elseif (Zone == 29) then -- Riverne Site #B01
if ((player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_COMPLETED) or (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar("StormsOfFate") > 2)) then -- Storms of Fate
skip = 1;
end
elseif (Zone == 31) then -- Monarch Linn
if (player:hasCompletedMission(COP, ANCIENT_VOWS)) then -- Ancient Vows
skip = 1;
elseif ((player:hasCompletedMission(COP, THE_SAVAGE)) or (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") > 1)) then
skip = 1;
end
elseif (Zone == 32) then -- Sealion's Den
if (player:hasCompletedMission(COP, ONE_TO_BE_FEARED)) then -- one_to_be_feared
skip = 1;
elseif (player:hasCompletedMission(COP, THE_WARRIOR_S_PATH)) then -- warriors_path
skip = 1;
end
elseif (Zone == 35) then -- The Garden of RuHmet
if ((player:hasCompletedMission(COP, WHEN_ANGELS_FALL)) or (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") > 4)) then -- when_angels_fall
skip = 1;
end
elseif (Zone == 36) then -- Empyreal Paradox
if ((player:hasCompletedMission(COP, DAWN)) or (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus") > 2)) then -- dawn
skip = 1;
end
elseif (Zone == 139) then -- Horlais Peak
if ((player:hasCompletedMission(BASTOK, THE_EMISSARY_SANDORIA2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_SANDORIA2)) or
((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") > 9)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(SANDORIA, THE_SECRET_WEAPON)) or (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") > 2)) then
skip = 1;
end
elseif (Zone == 140) then -- Ghelsba Outpost
if ((player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN)) or (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and player:getVar("MissionStatus") > 2)) then -- Sandy Mission 1-3
skip = 1;
elseif (player:hasCompleteQuest(SANDORIA, THE_HOLY_CREST)) then -- DRG Flag Quest
skip = 1;
end
elseif (Zone == 144) then -- Waughroon Shrine
if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_BASTOK2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_BASTOK2)) or
((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") > 10)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(BASTOK, ON_MY_WAY)) or (player:getCurrentMission(BASTOK) == ON_MY_WAY and player:getVar("MissionStatus") > 2)) then
skip = 1;
end
elseif (Zone == 146) then -- Balga's Dais
if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_WINDURST2) or player:hasCompletedMission(BASTOK, THE_EMISSARY_WINDURST2)) or
((player:getCurrentMission(SANDORIA) == JOURNEY_TO_WINDURST2 or player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST2) and player:getVar("MissionStatus") > 8)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(WINDURST, SAINTLY_INVITATION)) or (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") > 1)) then -- Mission 6-2
skip = 1;
end
elseif (Zone == 165) then -- Throne Room
if ((player:hasCompletedMission(player:getNation(), 15)) or (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") > 3)) then -- Mission 5-2
skip = 1;
end
elseif (Zone == 168) then -- Chamber of Oracles
if (player:hasCompletedMission(ZILART, THROUGH_THE_QUICKSAND_CAVES)) then -- Zilart Mission 6
skip = 1;
end
elseif (Zone == 170) then -- Full Moon Fountain
if ((player:hasCompleteQuest(WINDURST, THE_MOONLIT_PATH)) or (player:hasKeyItem(WHISPER_OF_THE_MOON))) then -- The Moonlit Path
skip = 1;
end
elseif (Zone == 179) then -- Stellar Fulcrum
if (player:hasCompletedMission(ZILART, RETURN_TO_DELKFUTTS_TOWER)) then -- Zilart Mission 8
skip = 1;
end
elseif (Zone == 180) then -- La'Loff Amphitheater
if (player:hasCompletedMission(ZILART, ARK_ANGELS)) then
skip = 1;
end
elseif (Zone == 181) then -- The Celestial Nexus
if (player:hasCompletedMission(ZILART, THE_CELESTIAL_NEXUS)) then -- Zilart Mission 16
skip = 1;
end
elseif (Zone == 201) then -- Cloister of Gales
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WIND)) or (player:hasKeyItem(WHISPER_OF_GALES))) then -- Trial by Wind
skip = 1;
end
elseif (Zone == 202) then -- Cloister of Storms
if ((player:hasCompleteQuest(OTHER_AREAS, TRIAL_BY_LIGHTNING)) or (player:hasKeyItem(WHISPER_OF_STORMS))) then -- Trial by Lightning
skip = 1;
end
elseif (Zone == 203) then -- Cloister of Frost
if ((player:hasCompleteQuest(SANDORIA, TRIAL_BY_ICE)) or (player:hasKeyItem(WHISPER_OF_FROST))) then -- Trial by Ice
skip = 1;
end
elseif (Zone == 206) then -- Qu'Bia Arena
if ((player:hasCompletedMission(player:getNation(), 14)) or (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") > 11)) then -- Mission 5-1
skip = 1;
elseif ((player:hasCompletedMission(player:getNation(), 23)) or (player:getCurrentMission(player:getNation()) == 23 and player:getVar("MissionStatus") > 4)) then -- Mission 9-2
skip = 1;
end
elseif (Zone == 207) then -- Cloister of Flames
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_FIRE)) or (player:hasKeyItem(WHISPER_OF_FLAMES))) then -- Trial by Fire
skip = 1;
end
elseif (Zone == 209) then -- Cloister of Tremors
if ((player:hasCompleteQuest(BASTOK, TRIAL_BY_EARTH)) or (player:hasKeyItem(WHISPER_OF_TREMORS))) then -- Trial by Earth
skip = 1;
end
elseif (Zone == 211) then -- Cloister of Tides
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WATER)) or (player:hasKeyItem(WHISPER_OF_TIDES))) then -- Trial by Water
skip = 1;
end
end
return skip;
end;
| gpl-3.0 |
Armyluix/darkstar | scripts/zones/Mhaura/npcs/Pikini-Mikini.lua | 36 | 1448 | -----------------------------------
-- Area: Mhaura
-- NPC: Pikini-Mikini
-- Standard Merchant NPC
-- @pos -48 -4 30 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIKINIMIKINI_SHOP_DIALOG);
stock = {0x1036,2335, --Eye Drops
0x1034,284, --Antidote
0x1037,720, --Echo Drops
0x1010,819, --Potion
0x119d,10, --Distilled Water
0x395,1821, --Parchment
0x43f3,9, --Lugworm
0x3fd,450, --Hatchet
0x1118,108, --Meat Jerky
0x14b3,133, --Salsa
0x0b33,9000} --Mhaura Waystone
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
otify/ProjectPorcupine | Assets/StreamingAssets/LUA/Overlay.lua | 5 | 1884 | -- Example of overlay function
-- Input: tile, the current tile for which the
-- overlay wants to display the data
-- Input: world, world class
-- Return: an integer (by default should be scaled between 0 and 255)
function oxygenValueAt(tile)
if tile == nil then
return 0
end
room = tile.room
if room == nil then
return 0
end
if (room.GetGasAmount("O2") > 0) then
return 128
end
return 0
end
-- Returns room id or null if room or tile invalid
function roomNumberValueAt(tile)
if tile == nil or tile.room == nil then
return 0
else
return tile.room.ID
end
end
-- Returns a magic value if furniture in tile is a power gen
function powerValueAt(tile)
zero = 128 -- This is middle between 0 and 256
multiplier = 12,8 -- For now 1 power is 40 in overlay
local powerComponent = ModUtils.GetPlugablePowerConnectionForTile(tile)
if (powerComponent == nil) then
return zero
end
if (powerComponent.IsConsumer) then
zero = zero - powerComponent.InputRate * multiplier
end
if (powerComponent.IsProducer) then
zero = zero + powerComponent.OutputRate * multiplier
end
return ModUtils.Clamp(zero, 0, 256)
end
-- Return temperature (in K) in current tile
function temperatureValueAt(tile, world)
--if world == nil or world.current == nil or world.current.temperature == nil then
-- return -1
--end
--if tile == nil then
-- return -2
--end
return math.max(math.min(world.temperature.GetTemperature(tile.X, tile.Y, tile.Z) / 3, 254), 0)
end
-- Returns coloring of thermal diffusivity of tile
function thermalDiffusivityValueAt(tile, world)
if tile == nil then
return 255
else
return 255
end
end
-- Dummy function, will be implemented
function heatGenerationValueAt(tile, world)
return 0
end
| gpl-3.0 |
isalnikov/Algorithm-Implementations | Gale_Shapely/Lua/Yonaba/gale_shapely_test.lua | 53 | 1896 | -- Tests for binary_search.lua
local binary_search = require 'binary_search'
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
run('Performs a binary search', function()
local t = {1, 2, 3, 4, 5}
assert(binary_search(t, 1) == 1)
assert(binary_search(t, 2) == 2)
assert(binary_search(t, 3) == 3)
assert(binary_search(t, 4) == 4)
assert(binary_search(t, 5) == 5)
end)
run('Array values do not have to be consecutive',function()
local t = {1, 3, 5, 10, 13}
assert(binary_search(t, 1) == 1)
assert(binary_search(t, 3) == 2)
assert(binary_search(t, 5) == 3)
assert(binary_search(t, 10) == 4)
assert(binary_search(t, 13) == 5)
end)
run('But the array needs to be sorted',function()
local t = {1, 15, 12, 14, 13}
assert(binary_search(t, 13) == nil)
assert(binary_search(t, 15) == nil)
end)
run('In case the value exists more than once, it returns any of them',function()
local t = {1, 12, 12, 13, 15, 15, 16}
assert(binary_search(t, 15) == 6)
assert(binary_search(t, 12) == 2)
end)
run('Accepts comparison functions for reversed arrays',function()
local t = {50, 33, 18, 12, 5, 1, 0}
local comp = function(a, b) return a > b end
assert(binary_search(t, 50, comp) == 1)
assert(binary_search(t, 33, comp) == 2)
assert(binary_search(t, 18, comp) == 3)
assert(binary_search(t, 12, comp) == 4)
assert(binary_search(t, 5, comp) == 5)
assert(binary_search(t, 1, comp) == 6)
assert(binary_search(t, 0, comp) == 7)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
abriasffxi/darkstar | scripts/zones/Ordelles_Caves/npcs/Treasure_Chest.lua | 17 | 4280 | -----------------------------------
-- Area: Ordelles Caves
-- NPC: Treasure Chest
-- Involved In Quest: Signed In Blood and The Goblin Tailor
-- @zone 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/treasure");
require("scripts/zones/Ordelles_Caves/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 43;
local TreasureMinLvL = 33;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--trade:hasItemQty(1030,1); -- Treasure Key
--trade:hasItemQty(1115,1); -- Skeleton Key
--trade:hasItemQty(1023,1); -- Living Key
--trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1030,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: Signed In Blood Quest -----------
if (player:getQuestStatus(SANDORIA,SIGNED_IN_BLOOD) == QUEST_ACCEPTED and player:getVar("SIGNED_IN_BLOOD_Prog") >= 1 and player:hasKeyItem(TORN_OUT_PAGES) == false) then
questItemNeeded = 1;
-- IMPORTANT ITEM: The Goblin Tailor Quest -----------
elseif (player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR) >= QUEST_ACCEPTED and VanadielRSELocation() == 0 and VanadielRSERace() == player:getRace() and player:hasKeyItem(MAGICAL_PATTERN) == false) then
questItemNeeded = 2;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
local respawn = false;
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(TORN_OUT_PAGES);
player:messageSpecial(KEYITEM_OBTAINED,TORN_OUT_PAGES);
elseif (questItemNeeded == 2) then
respawn = true;
player:addKeyItem(MAGICAL_PATTERN);
player:messageSpecial(KEYITEM_OBTAINED,MAGICAL_PATTERN);
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID(),respawn);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1030);
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 |
abriasffxi/darkstar | scripts/zones/Windurst_Woods/npcs/Mushuhi-Metahi.lua | 59 | 1052 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Mushuhi-Metahi
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x82718,0,0,0,0,0,0,0,VanadielTime());
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 |
Armyluix/darkstar | scripts/zones/Tavnazian_Safehold/npcs/_0q1.lua | 17 | 1908 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Sewer Entrance
-- @pos 28 -12 44 26
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THE_LOST_CITY and player:getVar("PromathiaStatus") > 0) then
player:startEvent(0x0067);
elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus")==3) then
player:startEvent(0x0074);
elseif (player:getCurrentMission(COP) >= DISTANT_BELIEFS or hasCompletedMission(COP,THE_LAST_VERSE)) then
player:startEvent(0x01f6);
else
--player:messageSpecial();
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0067) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_LOST_CITY);
player:addMission(COP,DISTANT_BELIEFS);
elseif (csid == 0x0074) then
player:setVar("PromathiaStatus",4);
elseif (csid == 0x01f6 and option == 1) then
player:setPos(260.068,0,-283.568,190,27); -- To Phomiuna Aqueducts {R}
end
end;
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/_0z0.lua | 17 | 1917 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- NPC: _0z0
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/globals/bcnm");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:addMission(COP, WHEN_ANGELS_FALL);
--player:setVar("PromathiaStatus",3);
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==3) then
player:startEvent(0x00CB);
elseif (EventTriggerBCNM(player,npc)) then
elseif (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==5) then
player:startEvent(0x00CD);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return 1;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if ( csid == 0x00CB) then
player:setVar("PromathiaStatus",4);
elseif (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
Armyluix/darkstar | scripts/zones/Al_Zahbi/npcs/Iphaaf.lua | 38 | 1025 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Iphaaf
-- Type: Mihli's Attendant
-- @zone: 48
-- @pos -28.014 -7 64.371
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00fe);
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 |
abriasffxi/darkstar | scripts/zones/Quicksand_Caves/mobs/Centurio_IV-VII.lua | 11 | 1351 | -----------------------------------
-- Area: Quicksand Caves
-- MOB: Centurio IV-VII
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDisengage Action
-----------------------------------
function onMobDisengage(mob)
local self = mob:getID();
DespawnMob(self, 120);
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (player:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US and player:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
-----------------------------------
-- onMobDespawn Action
-----------------------------------
function onMobDespawn(mob)
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if (GetServerVariable("BastokFight8_1") == 0) then
local npc = GetNPCByID(17629738); -- qm6
npc:setStatus(0); -- Reappear
end
end;
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Nashmau/npcs/Chichiroon.lua | 17 | 1298 | -----------------------------------
-- Area: Nashmau
-- NPC: Chichiroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHICHIROON_SHOP_DIALOG);
stock = {0x1579,99224, --Bolter's Die
0x157a,85500, --Caster's Die
0x157b,97350, --Courser's Die
0x157c,100650, --Blitzer's Die
0x157d,109440, --Tactician's Die
0x157e,116568} --Allies' Die
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Ezak91/CST-TMDB-Plugin | var/plugins/tmdb.lua | 1 | 8949 | --TMDB LUA Plugin
--From Ezak for coolstream.to
--READ LICENSE on https://github.com/Ezak91/CST-TMDB-Plugin.git
--2014
-- Aktuelle ChannelID für EPG Funktion ermitteln
function GetchannelID()
local fname = "../tmp/tmdb_channelid.txt"
os.execute("wget -q -O " .. fname .. " http://127.0.0.1/control/zapto" )
local fp = io.open(fname, "r")
if fp == nil then
print("Error opening file '" .. fname .. "'.")
end
channelID = fp:read()
fp:close()
end
--EPG zur aktuellen ChannelID ermitteln, parsen und pro Eintrag ein Menüitem erstellen
function GetEPG()
local fname = "../tmp/tmdb_epg.txt"
os.execute("wget -q -O " .. fname .. " 'http://127.0.0.1/control/epg?xml=true&channelid=" .. channelID .. "'" )
local fp = io.open(fname, "r")
if fp == nil then
print("Error opening file '" .. fname .. "'.")
os.exit(1)
else
local s = fp:read("*a")
fp:close()
titlenumber = 1
for title in string.gmatch(s, "<!%[CDATA%[(.-)%]%]>") do
if titlenumber == 1 then
channelname = title
m = menu.new{name=channelname}
titlenumber = titlenumber + 1
else
--Funktion zum hinzufügen des Menüitems
AddMenueitem(title)
end
end
ShowMenue()
end
end
--Funktion zum hinzufügen der EPG-Daten des aktuellen Channels
function AddMenueitem(_title)
m:addItem{type="string", action="GenLink", id=_title,name=_title}
end
--EPG-Menue anzeigen
function ShowMenue()
m:exec()
end
--Link zur Suche des Titels erstellen
function GenLink(_search)
lastSearch = _search
_search = _search:gsub("%s","%%20")
link = "http://api.themoviedb.org/3/search/" .. option .. "?api_key=311e70fd5d86a21b7ec0756a6067ac4d&language=de&query=" .. _search
Getquellcode( link)
end
--Quellcode einer Seite herunterladen zum Beispiel neue Kinofilme, oder Informationen zu einem gesuchten Film
function Getquellcode( _link)
local fname = "../tmp/tmdb_movies.txt"
os.execute("wget -q -O " .. fname .. " '" .. _link .. "'")
ParseMovies()
end
--Parsen der heruntergeladenen Movieinfos
function ParseMovies()
results = 0
movies = {}
local fname = "../tmp/tmdb_movies.txt"
local fp = io.open(fname, "r")
if fp == nil then
print("Error opening file '" .. fname .. "'.")
os.exit(1)
else
local s = fp:read("*a")
fp:close()
i = 1
results = s:match("total_results\":(%d)%}")
if results == '0' then
if option == 'movie' then
option = 'tv';
GenLink(lastSearch);
else
local h = hintbox.new{ title="Info", text="Leider keine Infos gefunden", icon="info"};
h:exec();
option = 'movie';
end
else
s = s:match("%[(.*)%]")
for movie in string.gmatch(s, "%{(.-)%}") do
movies[i] =
{
id = movie:match("id\":(.-),")
}
i = i + 1
end
movienumber = 1
if option == 'movie' then
GetMovieDetails();
else
GetTVDetails();
end
end
end
end
--Details zur ersten gefundenen MovieID parsen
function GetMovieDetails()
movieinfos = {}
movieinfos.titel = ""
movieinfos.originaltitel = ""
movieinfos.releasedate = ""
movieinfos.adult = ""
movieinfos.cover = ""
movieinfos.overview = ""
movieinfos.vote = ""
movieinfos.votecount = ""
movieinfos.runtime = ""
movieinfos.genres = " "
local fname = "../tmp/tmdb_moviedetails.txt"
os.execute("wget -q -O " .. fname .. " '" .. "http://api.themoviedb.org/3/movie/" .. movies[movienumber].id .. "?api_key=311e70fd5d86a21b7ec0756a6067ac4d&language=de" .. "'")
local fp = io.open(fname, "r")
if fp == nil then
print("Error opening file '" .. fname .. "'.")
os.exit(1)
else
local s = fp:read("*a")
fp:close()
movieinfos.titel = s:match("\"title\":\"(.-)\",")
movieinfos.originaltitel = s:match("original_title\":\"(.-)\",")
movieinfos.releasedate = s:match("release_date\":\"(.-)\",")
movieinfos.adult = s:match("adult\":(.-),")
movieinfos.cover = s:match("poster_path\":\"(.-)\",")
movieinfos.overview = s:match("overview\":\"(.-)\",")
movieinfos.vote = s:match("vote_average\":(.-),")
movieinfos.votecount = s:match("vote_count\":(.-)%}")
movieinfos.runtime = s:match("runtime\":(.-),")
--genres parsen
genrestmp = s:match("genres\":%[(.-)%}%]")
for genre in string.gmatch(genrestmp, "name\":\"(.-)\"") do
movieinfos.genres = movieinfos.genres .. " " .. genre
end
inhalt = "Titel: " .. movieinfos.titel .. "\n" .. "Original Titel: " .. movieinfos.originaltitel .. "\n" .. "Dauer: " .. movieinfos.runtime .. " min" .. "\n" .. "Releasedate: " .. movieinfos.releasedate .. "\n" .. "Genres: " .. movieinfos.genres .. "\n" .. "Adult: " .. movieinfos.adult .. "\n" .. "Bewertung: " .. movieinfos.vote .. " / 10 (" .. movieinfos.votecount .. " Stimmen)" .. "\n" .. "\n" .. "TMDB Plugin by Ezak for www.coolstream.to";
getPicture()
ShowInfo()
end
end
--Details zur ersten gefundenen SerienID parsen
function GetTVDetails()
movieinfos = {}
movieinfos.titel = ""
movieinfos.originaltitel = ""
movieinfos.releasedate = ""
movieinfos.cover = ""
movieinfos.overview = ""
movieinfos.vote = ""
movieinfos.votecount = ""
movieinfos.episodes = ""
movieinfos.seasons = ""
movieinfos.genres = " "
local fname = "../tmp/tmdb_moviedetails.txt"
os.execute("wget -q -O " .. fname .. " '" .. "http://api.themoviedb.org/3/tv/" .. movies[movienumber].id .. "?api_key=311e70fd5d86a21b7ec0756a6067ac4d&language=de" .. "'")
local fp = io.open(fname, "r")
if fp == nil then
print("Error opening file '" .. fname .. "'.")
os.exit(1)
else
local s = fp:read("*a")
fp:close()
movieinfos.titel = s:match("\",\"name\":\"(.-)\",")
movieinfos.originaltitel = s:match("original_name\":\"(.-)\",")
movieinfos.releasedate = s:match("first_air_date\":\"(.-)\",")
movieinfos.cover = s:match("poster_path\":\"(.-)\",")
movieinfos.overview = s:match("overview\":\"(.-)\",")
movieinfos.vote = s:match("vote_average\":(.-),")
movieinfos.votecount = s:match("vote_count\":(.-)%}")
movieinfos.seasons = s:match("number_of_seasons\":(.-),")
movieinfos.episodes = s:match("number_of_episodes\":(.-),")
--genres parsen
genrestmp = s:match("genres\":%[(.-)%}%]")
for genre in string.gmatch(genrestmp, "name\":\"(.-)\"") do
movieinfos.genres = movieinfos.genres .. " " .. genre
end
inhalt = "Titel: " .. movieinfos.titel .. "\n" .. "Original Titel: " .. movieinfos.originaltitel .. "\n" .. "Erstausstrahlung: " .. movieinfos.releasedate .. "\n" .. "Staffeln: " .. movieinfos.seasons .. "\n" .. "Episoden: " .. movieinfos.episodes .. "\n" .. "Genres: " .. movieinfos.genres .. "\n" .. "Bewertung: " .. movieinfos.vote .. " / 10 (" .. movieinfos.votecount .. " Stimmen)" .. "\n" .. "\n" .. "TMDB Plugin by Ezak for www.coolstream.to";
getPicture()
ShowInfo()
end
end
--Cover herunterladen
function getPicture()
if movieinfos.cover == nil then
local fname = "../tmp/tmdb_picture.jpg"
os.execute("wget -q -U Mozilla -O " .. fname .. " 'http://d3a8mw37cqal2z.cloudfront.net/assets/f996aa2014d2ffd/images/no-poster-w185.jpg'" );
else
local fname = "../tmp/tmdb_picture.jpg"
os.execute("wget -q -O " .. fname .. " '" .. "http://image.tmdb.org/t/p/w500" .. movieinfos.cover .. "'" )
end
end
--Infos im Fenster erzeugen
function ShowInfo()
oldOption = option;
n = neutrino();
local spacer = 8;
local x = 150;
local y = 70;
local dx = 1000;
local dy = 600;
if option == 'movie' then
btnGreenText = 'Serien';
else
btnGreenText = 'Filme';
end
utitel = "TMDB Info: " .. movieinfos.titel
w = cwindow.new{x=x, y=y, dx=dx, dy=dy, title=utitel, btnRed="Bild speichern",
btnGreen=btnGreenText};
w:paint();
ct1 = ctext.new{x=x+220, y=y+50, dx=500, dy=260, text=inhalt,font_text=FONT['MENU']};
ct1:paint();
ct2 = ctext.new{x=160, y=y+330, dx=1000, dy=230, text=movieinfos.overview,mode = "ALIGN_SCROLL"};
ct2:paint();
n:DisplayImage("/tmp/tmdb_picture.jpg", 160, 130, 190, 260)
neutrinoExec()
CloseNeutrino()
if oldOption == option then
option = 'movie';
else
GenLink(lastSearch);
end
end
--Fenster anzeigen und auf Tasteneingaben reagieren
function neutrinoExec()
repeat
msg, data = n:GetInput(500)
-- Taste Rot versteckt den Text
if (msg == RC['red']) then
--ct2:hide();
-- Taste Grün zeigt den Text wieder an
elseif (msg == RC['green']) then
if option == 'tv' then
option = 'movie';
else
option = 'tv';
end
msg = RC['home'];
-- Mit den Tasten up/down bzw. page_up/page_down kann der Text gescrollt werden,
-- falls erforderlich
elseif (msg == RC['up'] or msg == RC['page_up']) then
ct2:scroll{dir="up"};
elseif (msg == RC['down'] or msg == RC['page_down']) then
ct2:scroll{dir="down"};
end
-- Taste Exit oder Menü beendet das Fenster
until msg == RC['home'] or msg == RC['setup'];
end
--Fenster schließen
function CloseNeutrino()
ct1:hide();
ct2:hide();
w:hide();
end
--[[
MAIN
]]
option = 'movie';
GetchannelID();
GetEPG();
os.execute("rm /tmp/tmdb_*.*");
n = nil
m = nil
collectgarbage();
| mit |
Armyluix/darkstar | scripts/globals/abilities/pets/flaming_crush.lua | 25 | 1343 | ---------------------------------------------------
-- Flaming Crush M=10, 2, 2? (STILL don't know)
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/summon");
require("scripts/globals/magic");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local numhits = 3;
local accmod = 1;
local dmgmod = 10;
local dmgmodsubsequent = 1;
local totaldamage = 0;
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,dmgmodsubsequent,TP_NO_EFFECT,1,2,3);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE);
--get the resisted damage
damage.dmg = damage.dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1);
totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits);
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
Armyluix/darkstar | scripts/zones/Balgas_Dais/npcs/Burning_Circle.lua | 17 | 2294 | -----------------------------------
-- Area: Balga's Dais
-- NPC: Burning Circle
-- Balga's Dais Burning Circle
-- @pos 299 -123 345 146
-------------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/bcnm");
require("scripts/zones/Balgas_Dais/TextIDs");
---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad"
---- 1: Steamed Sprouts (BCNM 40, Star Orb)
---- 2: Divine Punishers (BCNM 60, Moon Orb)
---- 3: Saintly Invitation (Windurst mission 6-2)
---- 4: Treasure and Tribulations (BCNM 50, Comet Orb)
---- 5: Shattering Stars (MNK)
---- 6: Shattering Stars (WHM)
---- 7: Shattering Stars (SMN)
---- 8: Creeping Doom (BCNM 30, Sky Orb)
---- 9: Charming Trio (BCNM 20, Cloudy Orb)
---- 10: Harem Scarem (BCNM 30, Sky Orb)
---- 11: Early Bird Catches the Wyrm (KSNM 99, Themis Orb)
---- 12: Royal Succession (BCNM 40, Star Orb)
---- 13: Rapid Raptors (BCNM 50, Comet Orb)
---- 14: Wild Wild Whiskers (BCNM 60, Moon Orb)
---- 15: Season's Greetings (KSNM 30, Clotho Orb)
---- 16: Royale Ramble (KSNM 30, Lachesis Orb)
---- 17: Moa Constrictors (KSNM 30, Atropos Orb
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
tfryett/S4 | examples/magneto/halfspace.lua | 7 | 1758 | -- Infinite halfspace of magneto-optic material.
-- Assume the permittivity tensor in the receiving halfspace is
-- [ e ie' 0 ]
-- [ -ie' e 0 ]
-- [ 0 0 e ]
-- Then solving the wave equation gives two circular polarization modes:
-- E = (1, i)/sqrt(2), km = omega sqrt(e-ie)
-- E = (1,-i)/sqrt(2), kp = omega sqrt(e+ie)
-- For normal incidence, we match boundary conditions:
-- (E0+Erx, Ery) = a(1,i)/sqrt(2) + b(1,-i)/sqrt(2)
-- k0(E0-Erx, -Ery) = a km(1,i)/sqrt(2) + b kp(1,-i)/sqrt(2)
-- k0 = omega
-- Solving these gives
-- a = E0 k0/(k0+km)/sqrt(2), b = E0 k0/(k0+kp)/sqrt(2)
-- Er = E0/((k0+km)(k0+kp))/sqrt(2) (k0 k0 - km kp, i k0(kp-km))/sqrt(2)
-- The transmitted field is
-- Etx = Re[ E0 k0/sqrt(2) (exp(i km z)/(k0+km) + exp(i kp z)/(k0+kp)) ]
-- Ety = Re[ i E0 k0/sqrt(2) (exp(i km z)/(k0+km) - exp(i kp z)/(k0+kp)) ]
S = S4.NewSimulation()
S:SetLattice({1,0}, {0,1})
S:SetNumG(1)
f = 0.4
S:SetFrequency(f)
eps = 10
epsp = 3
S:AddMaterial("Dielectric", {
{eps, 0}, {0, epsp}, {0, 0},
{0, -epsp}, {eps, 0}, {0, 0},
{0, 0}, {0, 0}, {eps, 0}
})
S:AddMaterial("Vacuum", {1,0})
S:AddLayer('AirAbove', 0, 'Vacuum')
S:AddLayer('Stuff', 0, 'Dielectric')
S:SetExcitationPlanewave(
{0,0}, -- incidence angles (spherical coordinates: phi in [0,180], theta in [0,360])
{0,0}, -- s-polarization amplitude and phase (in degrees)
{1,0}) -- p-polarization amplitude and phase
k0 = 2*math.pi*f
km = k0*math.sqrt(eps-epsp)
kp = k0*math.sqrt(eps+epsp)
for z = 0,10,0.01 do
Exr,Eyr = S:GetEField({0,0,z})
Etx = (math.cos(km*z)/(k0+km) + math.cos(kp*z)/(k0+kp)) / f
Ety = -(math.sin(km*z)/(k0+km) - math.sin(kp*z)/(k0+kp)) / f
print(z, Exr,Etx, Eyr,Ety)
end
| gpl-2.0 |
ElectroDuk/QuackWars | garrysmod/gamemodes/Basewars(Broken}/gamemode/cl_buymenu.lua | 1 | 3000 | local Panel = vgui.Create( "DFrame" )
Panel:Hide()
hook.Add( "PopulateBasewars", "AddEntityContent", function( pnlContent, tree, node )
local Categorised = {}
-- Add this list into the tormoil
local SpawnableEntities = scripted_ents.GetSpawnable()
for k,v in pairs(SpawnableEntities) do --Remove all non basewars items
if v.Price == nil then
table.remove(SpawnableEntities, k)
end
end
if ( SpawnableEntities ) then
for k, v in pairs( SpawnableEntities ) do
v.Category = v.Category or "Other"
Categorised[ v.Category ] = Categorised[ v.Category ] or {}
table.insert( Categorised[ v.Category ], v )
end
end
--
-- Add a tree node for each category
--
for CategoryName, v in SortedPairs( Categorised ) do
-- Add a node to the tree
local node = tree:AddNode( CategoryName, "icon16/bricks.png" );
-- When we click on the node - populate it using this function
node.DoPopulate = function( self )
-- If we've already populated it - forget it.
if ( self.PropPanel ) then return end
-- Create the container panel
self.PropPanel = vgui.Create( "ContentContainer", pnlContent )
self.PropPanel:SetVisible( false )
self.PropPanel:SetTriggerSpawnlistChange( false )
for k, ent in SortedPairsByMemberValue( v, "PrintName" ) do
local Icon = spawnmenu.CreateContentIcon( ent.ScriptedEntityType or "entity", self.PropPanel,
{
nicename = ent.PrintName or ent.ClassName,
spawnname = ent.ClassName,
material = "materials/spawnicons/"..ent.Model,
admin = ent.AdminOnly || ( !ent.Spawnable && ent.AdminSpawnable )
})
Icon.DoClick = function ()
LocalPlayer():ConCommand("buy_entity "..ent.ClassName)
end
local Tooltip = Format( "Name: %s\nPrice: %s", ent.PrintName, ent.Price )
Icon:SetTooltip( Tooltip )
end
end
-- If we click on the node populate it and switch to it.
node.DoClick = function( self )
self:DoPopulate()
pnlContent:SwitchPanel( self.PropPanel );
end
end
-- Select the first node
local FirstNode = tree:Root():GetChildNode( 0 )
if ( IsValid( FirstNode ) ) then
FirstNode:InternalDoClick()
end
end )
spawnmenu.AddCreationTab( "Basewars", function()
local ctrl = vgui.Create( "SpawnmenuContentPanel" )
ctrl:CallPopulateHook( "PopulateBasewars" );
return ctrl
end, "icon16/basket.png", 20 )
| mit |
jameshilliard/WM2500RP-V1.0.0.34_gpl_src | package/uci/trigger/lib/trigger.lua | 40 | 8391 | module("uci.trigger", package.seeall)
require("posix")
require("uci")
local path = "/lib/config/trigger"
local triggers = nil
local tmp_cursor = nil
function load_modules()
if triggers ~= nil then
return
end
triggers = {
list = {},
uci = {},
active = {}
}
local modules = posix.glob(path .. "/*.lua")
if modules == nil then
return
end
local oldpath = package.path
package.path = path .. "/?.lua"
for i, v in ipairs(modules) do
pcall(require(string.gsub(v, path .. "/(%w+)%.lua$", "%1")))
end
package.path = oldpath
end
function check_table(table, name)
if table[name] == nil then
table[name] = {}
end
return table[name]
end
function get_table_val(val, vtype)
if type(val) == (vtype or "string") then
return { val }
elseif type(val) == "table" then
return val
end
return nil
end
function get_name_list(name)
return get_table_val(name or ".all")
end
function add_trigger_option(list, t)
local name = get_name_list(t.option)
for i, n in ipairs(name) do
option = check_table(list, n)
table.insert(option, t)
end
end
function add_trigger_section(list, t)
local name = get_name_list(t.section)
for i, n in ipairs(name) do
section = check_table(list, n)
add_trigger_option(section, t)
end
end
function check_insert_triggers(dest, list, tuple)
if list == nil then
return
end
for i, t in ipairs(list) do
local add = true
if type(t.check) == "function" then
add = t.check(tuple)
end
if add then
dest[t.id] = t
end
end
end
function find_section_triggers(tlist, pos, tuple)
if pos == nil then
return
end
check_insert_triggers(tlist, pos[".all"], tuple)
if tuple.option then
check_insert_triggers(tlist, pos[tuple.option], tuple)
end
end
function check_recursion(name, seen)
if seen == nil then
seen = {}
end
if seen[name] then
return nil
end
seen[name] = true
return seen
end
function find_recursive_depends(list, name, seen)
seen = check_recursion(name, seen)
if not seen then
return
end
local bt = get_table_val(triggers.list[name].belongs_to) or {}
for i, n in ipairs(bt) do
table.insert(list, n)
find_recursive_depends(list, n, seen)
end
end
function check_trigger_depth(list, name)
if name == nil then
return
end
local n = list[name]
if n == nil then
return
end
list[name] = nil
return check_trigger_depth(list, n)
end
function find_triggers(tuple)
local pos = triggers.uci[tuple.package]
if pos == nil then
return {}
end
local tlist = {}
find_section_triggers(tlist, pos[".all"], tuple)
find_section_triggers(tlist, pos[tuple.section[".type"]], tuple)
for n, t in pairs(tlist) do
local dep = {}
find_recursive_depends(dep, t.id)
for i, depname in ipairs(dep) do
check_trigger_depth(tlist, depname)
end
end
local nlist = {}
for n, t in pairs(tlist) do
if t then
table.insert(nlist, t)
end
end
return nlist
end
function reset_state()
assert(io.open("/var/run/uci_trigger", "w")):close()
if tctx then
tctx:unload("uci_trigger")
end
end
function load_state()
-- make sure the config file exists before we attempt to load it
-- uci doesn't like loading nonexistent config files
local f = assert(io.open("/var/run/uci_trigger", "a")):close()
load_modules()
triggers.active = {}
if tctx then
tctx:unload("uci_trigger")
else
tctx = uci.cursor()
end
assert(tctx:load("/var/run/uci_trigger"))
tctx:foreach("uci_trigger", "trigger",
function(section)
trigger = triggers.list[section[".name"]]
if trigger == nil then
return
end
active = {}
triggers.active[trigger.id] = active
local s = get_table_val(section["sections"]) or {}
for i, v in ipairs(s) do
active[v] = true
end
end
)
end
function get_names(list)
local slist = {}
for name, val in pairs(list) do
if val then
table.insert(slist, name)
end
end
return slist
end
function check_cancel(name, seen)
local t = triggers.list[name]
local dep = get_table_val(t.belongs_to)
seen = check_recursion(name, seen)
if not t or not dep or not seen then
return false
end
for i, v in ipairs(dep) do
-- only cancel triggers for all sections
-- if both the current and the parent trigger
-- are per-section
local section_only = false
if t.section_only then
local tdep = triggers.list[v]
if tdep then
section_only = tdep.section_only
end
end
if check_cancel(v, seen) then
return true
end
if triggers.active[v] then
if section_only then
for n, active in pairs(triggers.active[v]) do
triggers.active[name][n] = false
end
else
return true
end
end
end
return false
end
-- trigger api functions
function add(ts)
for i,t in ipairs(ts) do
triggers.list[t.id] = t
match = {}
if t.package then
local package = check_table(triggers.uci, t.package)
add_trigger_section(package, t)
triggers.list[t.id] = t
end
end
end
function save_trigger(name)
if triggers.active[name] then
local slist = get_names(triggers.active[name])
if #slist > 0 then
tctx:set("uci_trigger", name, "sections", slist)
end
else
tctx:delete("uci_trigger", name)
end
end
function set(data, cursor)
assert(data ~= nil)
if cursor == nil then
cursor = tmp_cursor or uci.cursor()
tmp_cursor = uci.cursor
end
local tuple = {
package = data[1],
section = data[2],
option = data[3],
value = data[4]
}
assert(cursor:load(tuple.package))
load_state()
local section = cursor:get_all(tuple.package, tuple.section)
if (section == nil) then
if option ~= nil then
return
end
section = {
[".type"] = value
}
if tuple.section == nil then
tuple.section = ""
section[".anonymous"] = true
end
section[".name"] = tuple.section
end
tuple.section = section
local ts = find_triggers(tuple)
for i, t in ipairs(ts) do
local active = triggers.active[t.id]
if not active then
active = {}
triggers.active[t.id] = active
tctx:set("uci_trigger", t.id, "trigger")
end
if section[".name"] then
active[section[".name"]] = true
end
save_trigger(t.id)
end
tctx:save("uci_trigger")
end
function get_description(trigger, sections)
if not trigger.title then
return trigger.id
end
local desc = trigger.title
if trigger.section_only and sections and #sections > 0 then
desc = desc .. " (" .. table.concat(sections, ", ") .. ")"
end
return desc
end
function get_active()
local slist = {}
if triggers == nil then
load_state()
end
for name, val in pairs(triggers.active) do
if val and not check_cancel(name) then
local sections = {}
for name, active in pairs(triggers.active[name]) do
if active then
table.insert(sections, name)
end
end
table.insert(slist, { triggers.list[name], sections })
end
end
return slist
end
function set_active(trigger, sections)
if triggers == nil then
load_state()
end
if not triggers.list[trigger] then
return
end
if triggers.active[trigger] == nil then
tctx:set("uci_trigger", trigger, "trigger")
triggers.active[trigger] = {}
end
local active = triggers.active[trigger]
if triggers.list[trigger].section_only or sections ~= nil then
for i, t in ipairs(sections) do
triggers.active[trigger][t] = true
end
end
save_trigger(trigger)
tctx:save("uci_trigger")
end
function clear_active(trigger, sections)
if triggers == nil then
load_state()
end
if triggers.list[trigger] == nil or triggers.active[trigger] == nil then
return
end
local active = triggers.active[trigger]
if not triggers.list[trigger].section_only or sections == nil then
triggers.active[trigger] = nil
else
for i, t in ipairs(sections) do
triggers.active[trigger][t] = false
end
end
save_trigger(trigger)
tctx:save("uci_trigger")
end
function run(ts)
if ts == nil then
ts = get_active()
end
for i, t in ipairs(ts) do
local trigger = t[1]
local sections = t[2]
local actions = get_table_val(trigger.action, "function") or {}
for ai, a in ipairs(actions) do
if not trigger.section_only then
sections = { "" }
end
for si, s in ipairs(sections) do
if a(s) then
tctx:delete("uci_trigger", trigger.id)
tctx:save("uci_trigger")
end
end
end
end
end
-- helper functions
function system_command(arg)
local cmd = arg
return function(arg)
return os.execute(cmd:format(arg)) == 0
end
end
function service_restart(arg)
return system_command("/etc/init.d/" .. arg .. " restart")
end
| gpl-2.0 |
ElectroDuk/QuackWars | garrysmod/gamemodes/Basewars/entities(maybe_outdated)/entities/radartower/init.lua | 2 | 5152 | -- ============================================
-- = =
-- = Crate SENT by Mahalis =
-- = =
-- ============================================
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:Initialize()
self.Entity:SetModel( "models/props_wasteland/gaspump001a.mdl")
self.Entity:PhysicsInit(SOLID_VPHYSICS)
self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
self.Entity:SetSolid(SOLID_VPHYSICS)
self.Entity:SetColor(0,0,0,1)
self.Dish2 = ents.Create("prop_dynamic_override")
self.Dish2:SetModel( "models/props_wasteland/gaspump001a.mdl" )
self.Dish2:SetPos(self.Entity:GetPos()+self.Entity:GetAngles():Up())
self.Dish2:SetAngles(Angle(0,0,0))
self.Dish2:SetParent(self.Entity)
self.Dish2:SetSolid(SOLID_NONE)
self.Dish2:SetMoveType(MOVETYPE_NONE)
local phys = self.Entity:GetPhysicsObject()
if(phys:IsValid()) then phys:Wake() end
self.Dish = ents.Create("prop_dynamic_override")
self.Dish:SetModel( "models/props_rooftop/roof_dish001.mdl" )
self.Dish:SetPos(self.Entity:GetPos()+self.Entity:GetAngles():Forward()*-5+self.Entity:GetAngles():Up()*25)
//self.Dish:SetAngles(Angle(0,90,90))
self.Dish:SetParent(self.Entity)
self.Dish:SetSolid(SOLID_NONE)
//self.Dish:PhysicsInit(SOLID_NONE)
self.Dish:SetMoveType(MOVETYPE_NONE)
timer.Create( tostring(self.Entity), 120, 0, self.giveMoney, self)
timer.Create( tostring(self.Entity) .. "fuckafkfags", 1200, 1, self.shutOff, self)
timer.Create( tostring(self.Entity) .. "notifyoff", 1080, 1, self.notifypl, self)
self.Entity:SetNWInt("damage",250)
self.Entity:SetNWInt("upgrade", 0)
local ply = self.Owner
ply:GetTable().maxtower=ply:GetTable().maxtower + 1
ply:GetTable().Tower = self.Entity
self.Inactive = false
self.Entity:SetNWInt("power",0)
self.Scans = 1
self.Entity:SetNWInt("scans", self.Scans)
self.scrap = false
self.BombNotify=false
end
function ENT:giveMoney()
local ply = self.Owner
if(ply:Alive() && !self.Inactive) then
self.Scans = self.Scans + 1
if self.Scans>10 then
Notify( ply, 4, 3, "Radar tower is fully charged at 10 charges.")
self.Scans = 10
else
// why did i bother? im not a grammar nazi.
if self.Scans!=1 then
Notify( ply, 2, 3, "Radar tower is ready to scan. " .. self.Scans .. " Charges available.")
else
Notify( ply, 2, 3, "Radar tower is ready to scan. 1 Charge available.")
end
end
elseif (self.Inactive) then
Notify( ply, 4, 3, "A radar tower is inactive, press use on it for it to continue charging" );
end
end
function ENT:shutOff()
local ply = self.Owner
self.Inactive = true
Notify( ply, 1, 3, "NOTICE: A RADAR TOWER HAS GONE INACTIVE" );
Notify( ply, 1, 3, "PRESS USE ON IT FOR IT TO BE ABLE TO KEEP CHARGING" );
self.Dish:SetColor(255,0,0,255)
self.Dish2:SetColor(255,0,0,255)
end
function ENT:notifypl()
local ply = self.Owner
Notify( ply, 4, 3, "NOTICE: A RADAR TOWER IS ABOUT TO GO INACTIVE" );
Notify( ply, 4, 3, "PRESS USE ON IT TO KEEP IT CHARGING" );
self.Dish:SetColor(255,150,150,255)
self.Dish2:SetColor(255,150,150,255)
end
function ENT:MakeScraps()
-- if !self.scrap then
-- self.scrap = false
-- local value = CfgVars["generatorcost"]/8
-- if value<5 then value = 5 end
-- for i=0, 5, 1 do
-- local scrapm = ents.Create("scrapmetal")
-- scrapm:SetModel( "models/gibs/metal_gib" .. math.random(1,5) .. ".mdl" );
-- local randpos = Vector(math.random(-5,5), math.random(-5,5), math.random(0,5))
-- scrapm:SetPos(self.Entity:GetPos()+randpos)
-- scrapm:Spawn()
-- scrapm:GetTable().ScrapMetal = true
-- scrapm:GetTable().Amount = math.random(3,value)
-- scrapm:Activate()
-- scrapm:GetPhysicsObject():SetVelocity(randpos*35)
--
-- timer.Create( "scraptimer" ..i, 10, 1, function(removeme)
-- removeme:Remove()
-- end, scrapm )
--
--
-- end
-- end
end
function ENT:Use(activator,caller)
timer.Destroy( tostring(self.Entity) .. "fuckafkfags")
timer.Create( tostring(self.Entity) .. "fuckafkfags", 1200, 1, self.shutOff, self)
timer.Destroy( tostring(self.Entity) .. "notifyoff")
timer.Create( tostring(self.Entity) .. "notifyoff", 1080, 1, self.notifypl, self)
self.Inactive = false
self.Dish:SetColor(255,255,255,255)
self.Dish2:SetColor(255,255,255,255)
end
function ENT:Think()
if (ValidEntity(self.Owner)==false) then
self.Entity:Remove()
end
self.Entity:NextThink(CurTime()+0.1)
self.Entity:SetNWInt("scans", self.Scans)
local pos = self.Entity:GetPos()
local sawbomb=false
for k,v in pairs(ents.FindByClass("bigbomb")) do
if v:GetPos():Distance(pos)<2048 then
sawbomb=true
if !self.BombNotify then
Notify(self.Owner,1,3, "Radar tower has detected a Big Bomb")
self.BombNotify=true
end
end
end
if !sawbomb then self.BombNotify=false end
return true
end
function ENT:OnRemove( )
timer.Destroy(tostring(self.Entity))
timer.Destroy(tostring(self.Entity) .. "fuckafkfags")
timer.Destroy(tostring(self.Entity) .. "notifyoff")
local ply = self.Owner
if ValidEntity(ply) then
ply:GetTable().maxtower=ply:GetTable().maxtower - 1
end
end
| mit |
Whit3Tig3R/ZeDspammbot | plugins/all.lua | 264 | 4202 | do
data = load_data(_config.moderation.data)
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)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_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
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'chat stats! \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return 'Group is not added.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group \n \n"
local settings = show_group_settings(target)
text = text.."Group settings \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\n"..modlist
local link = get_link(target)
text = text.."\n\n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
return
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end | gpl-2.0 |
Armyluix/darkstar | scripts/zones/Garlaige_Citadel/npcs/Mashira.lua | 17 | 2099 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: Mashira
-- Involved in Quests: Rubbish day, Making Amens!
-- @pos 141 -6 138 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,RUBBISH_DAY) == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 0) then
player:startEvent(0x000b,1); -- For the quest "Rubbish day"
elseif (player:getQuestStatus(WINDURST,MAKING_AMENS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(128) == true) then
player:startEvent(0x000b,3);
else player:startEvent(0x000b,0); -- Making Amens dialogue
end
else
player:startEvent(0x000b,3); -- Standard dialog and menu
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);
RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY);
MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS);
if (csid == 0x000b and option == 1 and RubbishDay == QUEST_ACCEPTED) then
player:delKeyItem(MAGIC_TRASH);
player:setVar("RubbishDayVar",1);
elseif (csid == 0x000b and option == 0 and MakingAmens == QUEST_ACCEPTED) then
player:addKeyItem(128); --Broken Wand
player:messageSpecial(KEYITEM_OBTAINED,128);
player:tradeComplete();
end
end;
| gpl-3.0 |
dimrain/ABTestingGateway | lib/abtesting/userinfo/ipParser.lua | 25 | 1259 |
local _M = {
_VERSION = '0.01'
}
local ffi = require("ffi")
ffi.cdef[[
struct in_addr {
uint32_t s_addr;
};
int inet_aton(const char *cp, struct in_addr *inp);
uint32_t ntohl(uint32_t netlong);
char *inet_ntoa(struct in_addr in);
uint32_t htonl(uint32_t hostlong);
]]
local C = ffi.C
local ip2long = function(ip)
local inp = ffi.new("struct in_addr[1]")
if C.inet_aton(ip, inp) ~= 0 then
return tonumber(C.ntohl(inp[0].s_addr))
end
return nil
end
local long2ip = function(long)
if type(long) ~= "number" then
return nil
end
local addr = ffi.new("struct in_addr")
addr.s_addr = C.htonl(long)
return ffi.string(C.inet_ntoa(addr))
end
_M.get = function()
local ClientIP = ngx.req.get_headers()["X-Real-IP"]
if ClientIP == nil then
ClientIP = ngx.req.get_headers()["X-Forwarded-For"]
if ClientIP then
local colonPos = string.find(ClientIP, ' ')
if colonPos then
ClientIP = string.sub(ClientIP, 1, colonPos - 1)
end
end
end
if ClientIP == nil then
ClientIP = ngx.var.remote_addr
end
if ClientIP then
ClientIP = ip2long(ClientIP)
end
return ClientIP
end
return _M
| mit |
abriasffxi/darkstar | scripts/zones/Kamihr_Drifts/npcs/LiseranDoorEntrance.lua | 27 | 1210 | -----------------------------------
-- Area: Kamihr Drifts
-- NPC: Liseran Door Entrance
-- Zones to Outer Ra'Kaznar (zone 274)
-- @zone 274
-- @pos -34.549 -181.334 -20.031
-----------------------------------
package.loaded["scripts/zones/Kamihr_Drifts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Kamihr_Drifts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0022);
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 == 0x0022 and option == 1) then
player:setPos(-39.846,-179.334,-19.921,131,274);
end
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/globals/weaponskills/herculean_slash.lua | 18 | 1592 | -----------------------------------
-- Herculean Slash
-- Great Sword weapon skill
-- Skill Level: 290
-- Paralyzes target. Duration of effect varies with TP.
-- Aligned with the Snow Gorget, Thunder Gorget & Breeze Gorget.
-- Aligned with the Snow Belt, Thunder Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: VIT:60%
-- As this is a magic-based weaponskill it is also modified by Magic Attack Bonus.
-- 100%TP 200%TP 300%TP
-- 3.50 3.50 3.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_ICE;
params.skill = SKILL_GSD;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.vit_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params);
if (damage > 0) then
local duration = (tp/1000 * 60)
if (target:hasStatusEffect(EFFECT_PARALYSIS) == false) then
target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Castle_Oztroja/npcs/Treasure_Coffer.lua | 13 | 4293 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Treasure Coffer
-- @zone 151
-- @pos
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1044,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1044,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local listAF = getAFbyZone(zone);
for nb = 1,#listAF,3 do
if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then
questItemNeeded = 2;
break
end
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then -- 0 or 1
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 2) then
for nb = 1,#listAF,3 do
if (mJob == listAF[nb]) then
player:addItem(listAF[nb + 2]);
player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]);
break
end
end
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1044);
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 |
sum2012/mame | 3rdparty/genie/tests/actions/codeblocks/codeblocks_files.lua | 21 | 1664 | --
-- tests/actions/codeblocks/codeblocks_files.lua
-- Validate generation of files block in CodeLite C/C++ projects.
-- Copyright (c) 2011 Jason Perkins and the Premake project
--
T.codeblocks_files = { }
local suite = T.codeblocks_files
local codeblocks = premake.codeblocks
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
premake.bake.buildconfigs()
prj = premake.solution.getproject(sln, 1)
codeblocks.files(prj)
end
--
-- Test grouping and nesting
--
function suite.SimpleSourceFile()
files { "hello.cpp" }
prepare()
test.capture [[
<Unit filename="hello.cpp">
</Unit>
]]
end
function suite.SingleFolderLevel()
files { "src/hello.cpp" }
prepare()
test.capture [[
<Unit filename="src/hello.cpp">
</Unit>
]]
end
function suite.MultipleFolderLevels()
files { "src/greetings/hello.cpp" }
prepare()
test.capture [[
<Unit filename="src/greetings/hello.cpp">
</Unit>
]]
end
--
-- Test source file type handling
--
function suite.CFileInCppProject()
files { "hello.c" }
prepare()
test.capture [[
<Unit filename="hello.c">
<Option compilerVar="CC" />
</Unit>
]]
end
function suite.WindowsResourceFile()
files { "hello.rc" }
prepare()
test.capture [[
<Unit filename="hello.rc">
<Option compilerVar="WINDRES" />
</Unit>
]]
end
function suite.PchFile()
files { "hello.h" }
pchheader "hello.h"
prepare()
test.capture [[
<Unit filename="hello.h">
<Option compilerVar="CPP" />
<Option compile="1" />
<Option weight="0" />
<Add option="-x c++-header" />
</Unit>
]]
end
| gpl-2.0 |
minin43/nzombies | gamemodes/nzombies/gamemode/player_class/sh_player_create.lua | 2 | 1241 | DEFINE_BASECLASS( "player_default" )
local PLAYER = {}
--
-- See gamemodes/base/player_class/player_default.lua for all overridable variables
--
PLAYER.WalkSpeed = 300
PLAYER.RunSpeed = 600
PLAYER.CanUseFlashlight = true
function PLAYER:SetupDataTables()
self.Player:NetworkVar("Bool", 0, "UsingSpecialWeapon")
end
function PLAYER:Init()
-- Don't forget Colours
-- This runs when the player is first brought into the game
-- print("create")
end
function PLAYER:Loadout()
-- Creation Tools
self.Player:Give( "weapon_physgun" )
self.Player:Give( "nz_multi_tool" )
timer.Simple(0.1, function()
if IsValid(self.Player) then
if !self.Player:HasWeapon( "weapon_physgun" ) then
self.Player:Give( "weapon_physgun" )
end
if !self.Player:HasWeapon( "nz_multi_tool" ) then
self.Player:Give( "nz_multi_tool" )
end
end
end)
end
function PLAYER:Spawn()
-- if we are in create or debuging make zombies target us
if nzRound:InState(ROUND_CREATE) or GetConVar( "nz_zombie_debug" ):GetBool() then --TODO this is bullshit?
self.Player:SetTargetPriority(TARGET_PRIORITY_PLAYER)
end
self.Player:SetUsingSpecialWeapon(false)
end
player_manager.RegisterClass( "player_create", PLAYER, "player_default" )
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Sealions_Den/npcs/_0w0.lua | 14 | 1998 | -----------------------------------
-- Area: Sealion's Den
-- NPC: Iron Gate
-- @pos 612 132 774 32
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/globals/titles");
require("scripts/globals/teleports");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x000D);
elseif (EventTriggerBCNM(player,npc)) then
return;
elseif (player:getCurrentMission(COP) > THE_WARRIOR_S_PATH) then
player:startEvent(0x000C);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
EventUpdateBCNM(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
if (csid == 0x000c and option == 1) then
toPalaceEntrance(player);
elseif (csid == 0x000D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,SLANDEROUS_UTTERINGS);
player:addMission(COP,THE_ENDURING_TUMULT_OF_WAR);
player:addTitle(THE_LOST_ONE);
end
end; | gpl-3.0 |
hamed9898/i4bot | bot/utils.lua | 239 | 13499 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
| gpl-2.0 |
b0oh/mal | lua/reader.lua | 36 | 3921 | local rex = require('rex_pcre')
local string = require('string')
local table = require('table')
local types = require('types')
local throw, Nil, Symbol, List = types.throw, types.Nil,
types.Symbol, types.List
local M = {}
Reader = {}
function Reader:new(tokens)
local newObj = {tokens = tokens, position = 1}
self.__index = self
return setmetatable(newObj, self)
end
function Reader:next()
self.position = self.position + 1
return self.tokens[self.position-1]
end
function Reader:peek()
return self.tokens[self.position]
end
function M.tokenize(str)
local results = {}
local re_pos = 1
local re = rex.new("[\\s,]*(~@|[\\[\\]{}()'`~^@]|\"(?:\\\\.|[^\\\\\"])*\"|;[^\n]*|[^\\s\\[\\]{}('\"`,;)]*)", rex.flags().EXTENDED)
while true do
local s, e, t = re:exec(str, re_pos)
if not s or s > e then break end
re_pos = e + 1
local val = string.sub(str,t[1],t[2])
if string.sub(val,1,1) ~= ";" then
table.insert(results, val)
end
end
return results
end
function M.read_atom(rdr)
local int_re = rex.new("^-?[0-9]+$")
local float_re = rex.new("^-?[0-9][0-9.]*$")
local token = rdr:next()
if int_re:exec(token) then return tonumber(token)
elseif float_re:exec(token) then return tonumber(token)
elseif string.sub(token,1,1) == '"' then
local sval = string.sub(token,2,string.len(token)-1)
sval = string.gsub(sval, '\\"', '"')
sval = string.gsub(sval, '\\n', '\n')
return sval
elseif string.sub(token,1,1) == ':' then
return "\177" .. string.sub(token,2)
elseif token == "nil" then return Nil
elseif token == "true" then return true
elseif token == "false" then return false
else return Symbol:new(token)
end
end
function M.read_sequence(rdr, start, last)
local ast = {}
local token = rdr:next()
if token ~= start then throw("expected '"..start.."'") end
token = rdr:peek()
while token ~= last do
if not token then throw("expected '"..last.."', got EOF") end
table.insert(ast, M.read_form(rdr))
token = rdr:peek()
end
rdr:next()
return ast
end
function M.read_list(rdr)
return types.List:new(M.read_sequence(rdr, '(', ')'))
end
function M.read_vector(rdr)
return types.Vector:new(M.read_sequence(rdr, '[', ']'))
end
function M.read_hash_map(rdr)
local seq = M.read_sequence(rdr, '{', '}')
return types._assoc_BANG(types.HashMap:new(), unpack(seq))
end
function M.read_form(rdr)
local token = rdr:peek()
if "'" == token then
rdr:next()
return List:new({Symbol:new('quote'), M.read_form(rdr)})
elseif '`' == token then
rdr:next()
return List:new({Symbol:new('quasiquote'), M.read_form(rdr)})
elseif '~' == token then
rdr:next()
return List:new({Symbol:new('unquote'), M.read_form(rdr)})
elseif '~@' == token then
rdr:next()
return List:new({Symbol:new('splice-unquote'), M.read_form(rdr)})
elseif '^' == token then
rdr:next()
local meta = M.read_form(rdr)
return List:new({Symbol:new('with-meta'), M.read_form(rdr), meta})
elseif '@' == token then
rdr:next()
return List:new({Symbol:new('deref'), M.read_form(rdr)})
elseif ')' == token then throw("unexpected ')'")
elseif '(' == token then return M.read_list(rdr)
elseif ']' == token then throw("unexpected ']'")
elseif '[' == token then return M.read_vector(rdr)
elseif '}' == token then throw("unexpected '}'")
elseif '{' == token then return M.read_hash_map(rdr)
else return M.read_atom(rdr)
end
end
function M.read_str(str)
local tokens = M.tokenize(str)
if #tokens == 0 then error(nil) end
return M.read_form(Reader:new(tokens))
end
return M
| mpl-2.0 |
Armyluix/darkstar | scripts/zones/Bastok_Markets/npcs/Gwill.lua | 17 | 2884 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Gwill
-- Starts & Ends Quest: The Return of the Adventurer
-- Involved in Quests: The Cold Light of Day, Riding on the Clouds
-- @zone 235
-- @pos 0 0 0
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
returnOfAdven = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
if (returnOfAdven == QUEST_ACCEPTED and trade:hasItemQty(628,1) and trade:getItemCount() == 1) then
player:startEvent(0x00f3);
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 2) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
pFame = player:getFameLevel(BASTOK);
FatherFigure = player:getQuestStatus(BASTOK,FATHER_FIGURE);
TheReturn = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
if (FatherFigure == QUEST_COMPLETED and TheReturn == QUEST_AVAILABLE and pFame >= 3) then
player:startEvent(0x00f2);
elseif (player:getQuestStatus(BASTOK,THE_COLD_LIGHT_OF_DAY) == QUEST_ACCEPTED) then
player:startEvent(0x0067);
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 == 0x00f2) then
player:addQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
elseif (csid == 0x00f3) then
if (player:getFreeSlotsCount() >= 1) then
player:tradeComplete();
player:addTitle(KULATZ_BRIDGE_COMPANION);
player:addItem(12498);
player:messageSpecial(ITEM_OBTAINED,12498);
player:addFame(BASTOK,BAS_FAME*80);
player:completeQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12498);
end
end
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/globals/spells/paralyze_ii.lua | 7 | 2316 | -----------------------------------------
-- Spell: Paralyze II
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point
-- Paralyze II value per point is '1' This is a constant set in the table 'merits'
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_PARALYSIS)) then -- Effect already on, do nothing
spell:setMsg(75);
else
-- Calculate duration.
local duration = 180;
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
-- Grabbing variables for paralyze potency
local pMND = caster:getStat(MOD_MND);
local mMND = target:getStat(MOD_MND);
local merits = caster:getMerit(MERIT_PARALYZE_II);
local dMND = (pMND - mMND);
-- Calculate potency.
local potency = (pMND + dMND)/5; -- Simplified from (2 * (pMND + dMND)) / 10
if (potency > 30) then
potency = 30;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
potency = potency * 2;
caster:delStatusEffect(EFFECT_SABOTEUR);
end
potency = potency + merits; --similar to Slow II, merit potency bonus is added after the cap
-- printf("Duration : %u",duration);
-- printf("Potency : %u",potency);
local resist = applyResistanceEffect(caster,spell,target,dMND,35,merits*2,EFFECT_PARALYSIS);
if (resist >= 0.5) then -- There are no quarter or less hits, if target resists more than .5 spell is resisted completely
if (target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then
spell:setMsg(236);
else
-- no effect
spell:setMsg(75);
end
else
-- resist
spell:setMsg(85);
end
end
return EFFECT_PARALYSIS;
end;
| gpl-3.0 |
b0oh/mal | lua/printer.lua | 14 | 1741 | local string = require('string')
local table = require('table')
local types = require('types')
local utils = require('utils')
local M = {}
function M._pr_str(obj, print_readably)
local _r = print_readably
if utils.instanceOf(obj, types.Symbol) then
return obj.val
elseif types._list_Q(obj) then
return "(" .. table.concat(utils.map(function(e)
return M._pr_str(e,_r) end, obj), " ") .. ")"
elseif types._vector_Q(obj) then
return "[" .. table.concat(utils.map(function(e)
return M._pr_str(e,_r) end, obj), " ") .. "]"
elseif types._hash_map_Q(obj) then
local res = {}
for k,v in pairs(obj) do
res[#res+1] = M._pr_str(k, _r)
res[#res+1] = M._pr_str(v, _r)
end
return "{".. table.concat(res, " ").."}"
elseif type(obj) == 'string' then
if string.sub(obj,1,1) == "\177" then
return ':' .. string.sub(obj,2)
else
if _r then
local sval = obj:gsub('\\', '\\\\')
sval = sval:gsub('"', '\\"')
sval = sval:gsub('\n', '\\n')
return '"' .. sval .. '"'
else
return obj
end
end
elseif obj == types.Nil then
return "nil"
elseif obj == true then
return "true"
elseif obj == false then
return "false"
elseif types._malfunc_Q(obj) then
return "(fn* "..M._pr_str(obj.params).." "..M._pr_str(obj.ast)..")"
elseif types._atom_Q(obj) then
return "(atom "..M._pr_str(obj.val)..")"
elseif type(obj) == 'function' then
return "#<function>"
else
return string.format("%s", obj)
end
end
return M
| mpl-2.0 |
xpol/luainstaller | lua/versions/luajit-2.1/dynasm/dasm_x86.lua | 32 | 71256 | ------------------------------------------------------------------------------
-- DynASM x86/x64 module.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
local x64 = x64
-- Module information:
local _info = {
arch = x64 and "x64" or "x86",
description = "DynASM x86/x64 module",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub
local concat, sort, remove = table.concat, table.sort, table.remove
local bit = bit or require("bit")
local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
-- int arg, 1 buffer pos:
"DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB",
-- action arg (1 byte), int arg, 1 buffer pos (reg/num):
"VREG", "SPACE",
-- ptrdiff_t arg, 1 buffer pos (address): !x64
"SETLABEL", "REL_A",
-- action arg (1 byte) or int arg, 2 buffer pos (link, offset):
"REL_LG", "REL_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (link):
"IMM_LG", "IMM_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (offset):
"LABEL_LG", "LABEL_PC",
-- action arg (1 byte), 1 buffer pos (offset):
"ALIGN",
-- action args (2 bytes), no buffer pos.
"EXTERN",
-- action arg (1 byte), no buffer pos.
"ESC",
-- no action arg, no buffer pos.
"MARK",
-- action arg (1 byte), no buffer pos, terminal action:
"SECTION",
-- no args, no buffer pos, terminal action:
"STOP"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number (dynamically generated below).
local map_action = {}
-- First action number. Everything below does not need to be escaped.
local actfirst = 256-#action_names
-- Action list buffer and string (only used to remove dupes).
local actlist = {}
local actstr = ""
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
-- VREG kind encodings, pre-shifted by 5 bits.
local map_vreg = {
["modrm.rm.m"] = 0x00,
["modrm.rm.r"] = 0x20,
["opcode"] = 0x20,
["sib.base"] = 0x20,
["sib.index"] = 0x40,
["modrm.reg"] = 0x80,
["vex.v"] = 0xa0,
["imm.hi"] = 0xc0,
}
-- Current number of VREG actions contributing to REX/VEX shrinkage.
local vreg_shrink_count = 0
------------------------------------------------------------------------------
-- Compute action numbers for action names.
for n,name in ipairs(action_names) do
local num = actfirst + n - 1
map_action[name] = num
end
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
local last = actlist[nn] or 255
actlist[nn] = nil -- Remove last byte.
if nn == 0 then nn = 1 end
out:write("static const unsigned char ", name, "[", nn, "] = {\n")
local s = " "
for n,b in ipairs(actlist) do
s = s..b..","
if #s >= 75 then
assert(out:write(s, "\n"))
s = " "
end
end
out:write(s, last, "\n};\n\n") -- Add last byte back.
end
------------------------------------------------------------------------------
-- Add byte to action list.
local function wputxb(n)
assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, a, num)
wputxb(assert(map_action[action], "bad action name `"..action.."'"))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Optionally add a VREG action.
local function wvreg(kind, vreg, psz, sk, defer)
if not vreg then return end
waction("VREG", vreg)
local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'")
if b < (sk or 0) then
vreg_shrink_count = vreg_shrink_count + 1
end
if not defer then
b = b + vreg_shrink_count * 8
vreg_shrink_count = 0
end
wputxb(b + (psz or 0))
end
-- Add call to embedded DynASM C code.
local function wcall(func, args)
wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true)
end
-- Delete duplicate action list chunks. A tad slow, but so what.
local function dedupechunk(offset)
local al, as = actlist, actstr
local chunk = char(unpack(al, offset+1, #al))
local orig = find(as, chunk, 1, true)
if orig then
actargs[1] = orig-1 -- Replace with original offset.
for i=offset+1,#al do al[i] = nil end -- Kill dupe.
else
actstr = as..chunk
end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
local offset = actargs[1]
if #actlist == offset then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
dedupechunk(offset)
wcall("put", actargs) -- Add call to dasm_put().
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped byte.
local function wputb(n)
if n >= actfirst then waction("ESC") end -- Need to escape byte.
wputxb(n)
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 10
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end
local n = next_global
if n > 246 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=10,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=10,next_global-1 do
out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=10,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = -1
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n < -256 then werror("too many extern labels") end
next_extern = n - 1
t[name] = n
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("Extern labels:\n")
for i=1,-next_extern-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=1,-next_extern-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = {} -- Ext. register name -> int. name.
local map_reg_rev = {} -- Int. register name -> ext. name.
local map_reg_num = {} -- Int. register name -> register number.
local map_reg_opsize = {} -- Int. register name -> operand size.
local map_reg_valid_base = {} -- Int. register name -> valid base register?
local map_reg_valid_index = {} -- Int. register name -> valid index register?
local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex.
local reg_list = {} -- Canonical list of int. register names.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for _PTx macros).
local addrsize = x64 and "q" or "d" -- Size for address operands.
-- Helper functions to fill register maps.
local function mkrmap(sz, cl, names)
local cname = format("@%s", sz)
reg_list[#reg_list+1] = cname
map_archdef[cl] = cname
map_reg_rev[cname] = cl
map_reg_num[cname] = -1
map_reg_opsize[cname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[cname] = true
map_reg_valid_index[cname] = true
end
if names then
for n,name in ipairs(names) do
local iname = format("@%s%x", sz, n-1)
reg_list[#reg_list+1] = iname
map_archdef[name] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = n-1
map_reg_opsize[iname] = sz
if sz == "b" and n > 4 then map_reg_needrex[iname] = false end
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
for i=0,(x64 and sz ~= "f") and 15 or 7 do
local needrex = sz == "b" and i > 3
local iname = format("@%s%x%s", sz, i, needrex and "R" or "")
if needrex then map_reg_needrex[iname] = true end
local name
if sz == "o" or sz == "y" then name = format("%s%d", cl, i)
elseif sz == "f" then name = format("st%d", i)
else name = format("r%d%s", i, sz == addrsize and "" or sz) end
map_archdef[name] = iname
if not map_reg_rev[iname] then
reg_list[#reg_list+1] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = i
map_reg_opsize[iname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
reg_list[#reg_list+1] = ""
end
-- Integer registers (qword, dword, word and byte sized).
if x64 then
mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"})
end
mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"})
mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"})
mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"})
map_reg_valid_index[map_archdef.esp] = false
if x64 then map_reg_valid_index[map_archdef.rsp] = false end
if x64 then map_reg_needrex[map_archdef.Rb] = true end
map_archdef["Ra"] = "@"..addrsize
-- FP registers (internally tword sized, but use "f" as operand size).
mkrmap("f", "Rf")
-- SSE registers (oword sized, but qword and dword accessible).
mkrmap("o", "xmm")
-- AVX registers (yword sized, but oword, qword and dword accessible).
mkrmap("y", "ymm")
-- Operand size prefixes to codes.
local map_opsize = {
byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y",
tword = "t", aword = addrsize,
}
-- Operand size code to number.
local map_opsizenum = {
b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10,
}
-- Operand size code to name.
local map_opsizename = {
b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword",
t = "tword", f = "fpword",
}
-- Valid index register scale factors.
local map_xsc = {
["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3,
}
-- Condition codes.
local map_cc = {
o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7,
s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15,
c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7,
pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15,
}
-- Reverse defines for registers.
function _M.revdef(s)
return gsub(s, "@%w+", map_reg_rev)
end
-- Dump register names and numbers
local function dumpregs(out)
out:write("Register names, sizes and internal numbers:\n")
for _,reg in ipairs(reg_list) do
if reg == "" then
out:write("\n")
else
local name = map_reg_rev[reg]
local num = map_reg_num[reg]
local opsize = map_opsizename[map_reg_opsize[reg]]
out:write(format(" %-5s %-8s %s\n", name, opsize,
num < 0 and "(variable)" or num))
end
end
end
------------------------------------------------------------------------------
-- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC).
local function wputlabel(aprefix, imm, num)
if type(imm) == "number" then
if imm < 0 then
waction("EXTERN")
wputxb(aprefix == "IMM_" and 0 or 1)
imm = -imm-1
else
waction(aprefix.."LG", nil, num);
end
wputxb(imm)
else
waction(aprefix.."PC", imm, num)
end
end
-- Put signed byte or arg.
local function wputsbarg(n)
if type(n) == "number" then
if n < -128 or n > 127 then
werror("signed immediate byte out of range")
end
if n < 0 then n = n + 256 end
wputb(n)
else waction("IMM_S", n) end
end
-- Put unsigned byte or arg.
local function wputbarg(n)
if type(n) == "number" then
if n < 0 or n > 255 then
werror("unsigned immediate byte out of range")
end
wputb(n)
else waction("IMM_B", n) end
end
-- Put unsigned word or arg.
local function wputwarg(n)
if type(n) == "number" then
if shr(n, 16) ~= 0 then
werror("unsigned immediate word out of range")
end
wputb(band(n, 255)); wputb(shr(n, 8));
else waction("IMM_W", n) end
end
-- Put signed or unsigned dword or arg.
local function wputdarg(n)
local tn = type(n)
if tn == "number" then
wputb(band(n, 255))
wputb(band(shr(n, 8), 255))
wputb(band(shr(n, 16), 255))
wputb(shr(n, 24))
elseif tn == "table" then
wputlabel("IMM_", n[1], 1)
else
waction("IMM_D", n)
end
end
-- Put operand-size dependent number or arg (defaults to dword).
local function wputszarg(sz, n)
if not sz or sz == "d" or sz == "q" then wputdarg(n)
elseif sz == "w" then wputwarg(n)
elseif sz == "b" then wputbarg(n)
elseif sz == "s" then wputsbarg(n)
else werror("bad operand size") end
end
-- Put multi-byte opcode with operand-size dependent modifications.
local function wputop(sz, op, rex, vex, vregr, vregxb)
local psz, sk = 0, nil
if vex then
local tail
if vex.m == 1 and band(rex, 11) == 0 then
if x64 and vregxb then
sk = map_vreg["modrm.reg"]
else
wputb(0xc5)
tail = shl(bxor(band(rex, 4), 4), 5)
psz = 3
end
end
if not tail then
wputb(0xc4)
wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m)
tail = shl(band(rex, 8), 4)
psz = 4
end
local reg, vreg = 0, nil
if vex.v then
reg = vex.v.reg
if not reg then werror("bad vex operand") end
if reg < 0 then reg = 0; vreg = vex.v.vreg end
end
if sz == "y" or vex.l then tail = tail + 4 end
wputb(tail + shl(bxor(reg, 15), 3) + vex.p)
wvreg("vex.v", vreg)
rex = 0
if op >= 256 then werror("bad vex opcode") end
else
if rex ~= 0 then
if not x64 then werror("bad operand size") end
elseif (vregr or vregxb) and x64 then
rex = 0x10
sk = map_vreg["vex.v"]
end
end
local r
if sz == "w" then wputb(102) end
-- Needs >32 bit numbers, but only for crc32 eax, word [ebx]
if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end
if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end
if op >= 65536 then
if rex ~= 0 then
local opc3 = band(op, 0xffff00)
if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then
wputb(64 + band(rex, 15)); rex = 0; psz = 2
end
end
wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1
end
if op >= 256 then
local b = shr(op, 8)
if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end
wputb(b); op = band(op, 255); psz = psz + 1
end
if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end
if sz == "b" then op = op - 1 end
wputb(op)
return psz, sk
end
-- Put ModRM or SIB formatted byte.
local function wputmodrm(m, s, rm, vs, vrm)
assert(m < 4 and s < 16 and rm < 16, "bad modrm operands")
wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7))
end
-- Put ModRM/SIB plus optional displacement.
local function wputmrmsib(t, imark, s, vsreg, psz, sk)
local vreg, vxreg
local reg, xreg = t.reg, t.xreg
if reg and reg < 0 then reg = 0; vreg = t.vreg end
if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end
if s < 0 then s = 0 end
-- Register mode.
if sub(t.mode, 1, 1) == "r" then
wputmodrm(3, s, reg)
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.r", vreg, psz+1, sk)
return
end
local disp = t.disp
local tdisp = type(disp)
-- No base register?
if not reg then
local riprel = false
if xreg then
-- Indexed mode with index register only.
-- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp)
wputmodrm(0, s, 4)
if imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg)
wputmodrm(t.xsc, xreg, 5)
wvreg("sib.index", vxreg, psz+2, sk)
else
-- Pure 32 bit displacement.
if x64 and tdisp ~= "table" then
wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
wputmodrm(0, 4, 5)
else
riprel = x64
wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
end
end
if riprel then -- Emit rip-relative displacement.
if match("UWSiI", imark) then
werror("NYI: rip-relative displacement followed by immediate")
end
-- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f.
wputlabel("REL_", disp[1], 2)
else
wputdarg(disp)
end
return
end
local m
if tdisp == "number" then -- Check displacement size at assembly time.
if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too)
if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0]
elseif disp >= -128 and disp <= 127 then m = 1
else m = 2 end
elseif tdisp == "table" then
m = 2
end
-- Index register present or esp as base register: need SIB encoding.
if xreg or band(reg, 7) == 4 then
wputmodrm(m or 2, s, 4) -- ModRM.
if m == nil or imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg)
wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB.
wvreg("sib.index", vxreg, psz+2, sk, vreg)
wvreg("sib.base", vreg, psz+2, sk)
else
wputmodrm(m or 2, s, reg) -- ModRM.
if (imark == "I" and (m == 1 or m == 2)) or
(m == nil and (vsreg or vreg)) then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.m", vreg, psz+1, sk)
end
-- Put displacement.
if m == 1 then wputsbarg(disp)
elseif m == 2 then wputdarg(disp)
elseif m == nil then waction("DISP", disp) end
end
------------------------------------------------------------------------------
-- Return human-readable operand mode string.
local function opmodestr(op, args)
local m = {}
for i=1,#args do
local a = args[i]
m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?")
end
return op.." "..concat(m, ",")
end
-- Convert number to valid integer or nil.
local function toint(expr)
local n = tonumber(expr)
if n then
if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then
werror("bad integer number `"..expr.."'")
end
return n
end
end
-- Parse immediate expression.
local function immexpr(expr)
-- &expr (pointer)
if sub(expr, 1, 1) == "&" then
return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2))
end
local prefix = sub(expr, 1, 2)
-- =>expr (pc label reference)
if prefix == "=>" then
return "iJ", sub(expr, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "iJ", map_global[sub(expr, 3)]
end
-- [<>][1-9] (local label reference)
local dir, lnum = match(expr, "^([<>])([1-9])$")
if dir then -- Fwd: 247-255, Bkwd: 1-9.
return "iJ", lnum + (dir == ">" and 246 or 0)
end
local extname = match(expr, "^extern%s+(%S+)$")
if extname then
return "iJ", map_extern[extname]
end
-- expr (interpreted as immediate)
return "iI", expr
end
-- Parse displacement expression: +-num, +-expr, +-opsize*num
local function dispexpr(expr)
local disp = expr == "" and 0 or toint(expr)
if disp then return disp end
local c, dispt = match(expr, "^([+-])%s*(.+)$")
if c == "+" then
expr = dispt
elseif not c then
werror("bad displacement expression `"..expr.."'")
end
local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$")
local ops, imm = map_opsize[opsize], toint(tailops)
if ops and imm then
if c == "-" then imm = -imm end
return imm*map_opsizenum[ops]
end
local mode, iexpr = immexpr(dispt)
if mode == "iJ" then
if c == "-" then werror("cannot invert label reference") end
return { iexpr }
end
return expr -- Need to return original signed expression.
end
-- Parse register or type expression.
local function rtexpr(expr)
if not expr then return end
local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
local rnum = map_reg_num[reg]
if not rnum then
werror("type `"..(tname or expr).."' needs a register override")
end
if not map_reg_valid_base[reg] then
werror("bad base register override `"..(map_reg_rev[reg] or reg).."'")
end
return reg, rnum, tp
end
return expr, map_reg_num[expr]
end
-- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }.
local function parseoperand(param)
local t = {}
local expr = param
local opsize, tailops = match(param, "^(%w+)%s*(.+)$")
if opsize then
t.opsize = map_opsize[opsize]
if t.opsize then expr = tailops end
end
local br = match(expr, "^%[%s*(.-)%s*%]$")
repeat
if br then
t.mode = "xm"
-- [disp]
t.disp = toint(br)
if t.disp then
t.mode = x64 and "xm" or "xmO"
break
end
-- [reg...]
local tp
local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if not t.reg then
-- [expr]
t.mode = x64 and "xm" or "xmO"
t.disp = dispexpr("+"..br)
break
end
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr]
local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$")
if xsc then
if not map_reg_valid_index[reg] then
werror("bad index register `"..map_reg_rev[reg].."'")
end
t.xsc = map_xsc[xsc]
t.xreg = t.reg
t.vxreg = t.vreg
t.reg = nil
t.vreg = nil
t.disp = dispexpr(tailsc)
break
end
if not map_reg_valid_base[reg] then
werror("bad base register `"..map_reg_rev[reg].."'")
end
-- [reg] or [reg+-disp]
t.disp = toint(tailr) or (tailr == "" and 0)
if t.disp then break end
-- [reg+xreg...]
local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$")
xreg, t.xreg, tp = rtexpr(xreg)
if not t.xreg then
-- [reg+-expr]
t.disp = dispexpr(tailr)
break
end
if not map_reg_valid_index[xreg] then
werror("bad index register `"..map_reg_rev[xreg].."'")
end
if t.xreg == -1 then
t.vxreg, tailx = match(tailx, "^(%b())(.*)$")
if not t.vxreg then werror("bad variable register expression") end
end
-- [reg+xreg*xsc...]
local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$")
if xsc then
t.xsc = map_xsc[xsc]
tailx = tailsc
end
-- [...] or [...+-disp] or [...+-expr]
t.disp = dispexpr(tailx)
else
-- imm or opsize*imm
local imm = toint(expr)
if not imm and sub(expr, 1, 1) == "*" and t.opsize then
imm = toint(sub(expr, 2))
if imm then
imm = imm * map_opsizenum[t.opsize]
t.opsize = nil
end
end
if imm then
if t.opsize then werror("bad operand size override") end
local m = "i"
if imm == 1 then m = m.."1" end
if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end
if imm >= -128 and imm <= 127 then m = m.."S" end
t.imm = imm
t.mode = m
break
end
local tp
local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if t.reg then
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- reg
if tailr == "" then
if t.opsize then werror("bad operand size override") end
t.opsize = map_reg_opsize[reg]
if t.opsize == "f" then
t.mode = t.reg == 0 and "fF" or "f"
else
if reg == "@w4" or (x64 and reg == "@d4") then
wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'"))
end
t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm")
end
t.needrex = map_reg_needrex[reg]
break
end
-- type[idx], type[idx].field, type->field -> [reg+offset_expr]
if not tp then werror("bad operand `"..param.."'") end
t.mode = "xm"
t.disp = format(tp.ctypefmt, tailr)
else
t.mode, t.imm = immexpr(expr)
if sub(t.mode, -1) == "J" then
if t.opsize and t.opsize ~= addrsize then
werror("bad operand size override")
end
t.opsize = addrsize
end
end
end
until true
return t
end
------------------------------------------------------------------------------
-- x86 Template String Description
-- ===============================
--
-- Each template string is a list of [match:]pattern pairs,
-- separated by "|". The first match wins. No match means a
-- bad or unsupported combination of operand modes or sizes.
--
-- The match part and the ":" is omitted if the operation has
-- no operands. Otherwise the first N characters are matched
-- against the mode strings of each of the N operands.
--
-- The mode string for each operand type is (see parseoperand()):
-- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl
-- FP register: "f", +"F" for st0
-- Index operand: "xm", +"O" for [disp] (pure offset)
-- Immediate: "i", +"S" for signed 8 bit, +"1" for 1,
-- +"I" for arg, +"P" for pointer
-- Any: +"J" for valid jump targets
--
-- So a match character "m" (mixed) matches both an integer register
-- and an index operand (to be encoded with the ModRM/SIB scheme).
-- But "r" matches only a register and "x" only an index operand
-- (e.g. for FP memory access operations).
--
-- The operand size match string starts right after the mode match
-- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty.
-- The effective data size of the operation is matched against this list.
--
-- If only the regular "b", "w", "d", "q", "t" operand sizes are
-- present, then all operands must be the same size. Unspecified sizes
-- are ignored, but at least one operand must have a size or the pattern
-- won't match (use the "byte", "word", "dword", "qword", "tword"
-- operand size overrides. E.g.: mov dword [eax], 1).
--
-- If the list has a "1" or "2" prefix, the operand size is taken
-- from the respective operand and any other operand sizes are ignored.
-- If the list contains only ".", all operand sizes are ignored.
-- If the list has a "/" prefix, the concatenated (mixed) operand sizes
-- are compared to the match.
--
-- E.g. "rrdw" matches for either two dword registers or two word
-- registers. "Fx2dq" matches an st0 operand plus an index operand
-- pointing to a dword (float) or qword (double).
--
-- Every character after the ":" is part of the pattern string:
-- Hex chars are accumulated to form the opcode (left to right).
-- "n" disables the standard opcode mods
-- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q")
-- "X" Force REX.W.
-- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode.
-- "m"/"M" generates ModRM/SIB from the 1st/2nd operand.
-- The spare 3 bits are either filled with the last hex digit or
-- the result from a previous "r"/"R". The opcode is restored.
-- "u" Use VEX encoding, vvvv unused.
-- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is
-- removed from the list used by future characters).
-- "L" Force VEX.L
--
-- All of the following characters force a flush of the opcode:
-- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand.
-- "s" stores a 4 bit immediate from the last register operand,
-- followed by 4 zero bits.
-- "S" stores a signed 8 bit immediate from the last operand.
-- "U" stores an unsigned 8 bit immediate from the last operand.
-- "W" stores an unsigned 16 bit immediate from the last operand.
-- "i" stores an operand sized immediate from the last operand.
-- "I" dito, but generates an action code to optionally modify
-- the opcode (+2) for a signed 8 bit immediate.
-- "J" generates one of the REL action codes from the last operand.
--
------------------------------------------------------------------------------
-- Template strings for x86 instructions. Ordered by first opcode byte.
-- Unimplemented opcodes (deliberate omissions) are marked with *.
local map_op = {
-- 00-05: add...
-- 06: *push es
-- 07: *pop es
-- 08-0D: or...
-- 0E: *push cs
-- 0F: two byte opcode prefix
-- 10-15: adc...
-- 16: *push ss
-- 17: *pop ss
-- 18-1D: sbb...
-- 1E: *push ds
-- 1F: *pop ds
-- 20-25: and...
es_0 = "26",
-- 27: *daa
-- 28-2D: sub...
cs_0 = "2E",
-- 2F: *das
-- 30-35: xor...
ss_0 = "36",
-- 37: *aaa
-- 38-3D: cmp...
ds_0 = "3E",
-- 3F: *aas
inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m",
dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m",
push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or
"rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i",
pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m",
-- 60: *pusha, *pushad, *pushaw
-- 61: *popa, *popad, *popaw
-- 62: *bound rdw,x
-- 63: x86: *arpl mw,rw
movsxd_2 = x64 and "rm/qd:63rM",
fs_0 = "64",
gs_0 = "65",
o16_0 = "66",
a16_0 = not x64 and "67" or nil,
a32_0 = x64 and "67",
-- 68: push idw
-- 69: imul rdw,mdw,idw
-- 6A: push ib
-- 6B: imul rdw,mdw,S
-- 6C: *insb
-- 6D: *insd, *insw
-- 6E: *outsb
-- 6F: *outsd, *outsw
-- 70-7F: jcc lb
-- 80: add... mb,i
-- 81: add... mdw,i
-- 82: *undefined
-- 83: add... mdw,S
test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi",
-- 86: xchg rb,mb
-- 87: xchg rdw,mdw
-- 88: mov mb,r
-- 89: mov mdw,r
-- 8A: mov r,mb
-- 8B: mov r,mdw
-- 8C: *mov mdw,seg
lea_2 = "rx1dq:8DrM",
-- 8E: *mov seg,mdw
-- 8F: pop mdw
nop_0 = "90",
xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm",
cbw_0 = "6698",
cwde_0 = "98",
cdqe_0 = "4898",
cwd_0 = "6699",
cdq_0 = "99",
cqo_0 = "4899",
-- 9A: *call iw:idw
wait_0 = "9B",
fwait_0 = "9B",
pushf_0 = "9C",
pushfd_0 = not x64 and "9C",
pushfq_0 = x64 and "9C",
popf_0 = "9D",
popfd_0 = not x64 and "9D",
popfq_0 = x64 and "9D",
sahf_0 = "9E",
lahf_0 = "9F",
mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi",
movsb_0 = "A4",
movsw_0 = "66A5",
movsd_0 = "A5",
cmpsb_0 = "A6",
cmpsw_0 = "66A7",
cmpsd_0 = "A7",
-- A8: test Rb,i
-- A9: test Rdw,i
stosb_0 = "AA",
stosw_0 = "66AB",
stosd_0 = "AB",
lodsb_0 = "AC",
lodsw_0 = "66AD",
lodsd_0 = "AD",
scasb_0 = "AE",
scasw_0 = "66AF",
scasd_0 = "AF",
-- B0-B7: mov rb,i
-- B8-BF: mov rdw,i
-- C0: rol... mb,i
-- C1: rol... mdw,i
ret_1 = "i.:nC2W",
ret_0 = "C3",
-- C4: *les rdw,mq
-- C5: *lds rdw,mq
-- C6: mov mb,i
-- C7: mov mdw,i
-- C8: *enter iw,ib
leave_0 = "C9",
-- CA: *retf iw
-- CB: *retf
int3_0 = "CC",
int_1 = "i.:nCDU",
into_0 = "CE",
-- CF: *iret
-- D0: rol... mb,1
-- D1: rol... mdw,1
-- D2: rol... mb,cl
-- D3: rol... mb,cl
-- D4: *aam ib
-- D5: *aad ib
-- D6: *salc
-- D7: *xlat
-- D8-DF: floating point ops
-- E0: *loopne
-- E1: *loope
-- E2: *loop
-- E3: *jcxz, *jecxz
-- E4: *in Rb,ib
-- E5: *in Rdw,ib
-- E6: *out ib,Rb
-- E7: *out ib,Rdw
call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J",
jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB
-- EA: *jmp iw:idw
-- EB: jmp ib
-- EC: *in Rb,dx
-- ED: *in Rdw,dx
-- EE: *out dx,Rb
-- EF: *out dx,Rdw
lock_0 = "F0",
int1_0 = "F1",
repne_0 = "F2",
repnz_0 = "F2",
rep_0 = "F3",
repe_0 = "F3",
repz_0 = "F3",
-- F4: *hlt
cmc_0 = "F5",
-- F6: test... mb,i; div... mb
-- F7: test... mdw,i; div... mdw
clc_0 = "F8",
stc_0 = "F9",
-- FA: *cli
cld_0 = "FC",
std_0 = "FD",
-- FE: inc... mb
-- FF: inc... mdw
-- misc ops
not_1 = "m:F72m",
neg_1 = "m:F73m",
mul_1 = "m:F74m",
imul_1 = "m:F75m",
div_1 = "m:F76m",
idiv_1 = "m:F77m",
imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi",
imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi",
movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:",
movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:",
bswap_1 = "rqd:0FC8r",
bsf_2 = "rmqdw:0FBCrM",
bsr_2 = "rmqdw:0FBDrM",
bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU",
btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU",
btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU",
bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU",
shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:",
shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:",
rdtsc_0 = "0F31", -- P1+
rdpmc_0 = "0F33", -- P6+
cpuid_0 = "0FA2", -- P1+
-- floating point ops
fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m",
fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m",
fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m",
fpop_0 = "DDD8", -- Alias for fstp st0.
fist_1 = "xw:nDF2m|xd:DB2m",
fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m",
fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m",
fxch_0 = "D9C9",
fxch_1 = "ff:D9C8r",
fxch_2 = "fFf:D9C8r|Fff:D9C8R",
fucom_1 = "ff:DDE0r",
fucom_2 = "Fff:DDE0R",
fucomp_1 = "ff:DDE8r",
fucomp_2 = "Fff:DDE8R",
fucomi_1 = "ff:DBE8r", -- P6+
fucomi_2 = "Fff:DBE8R", -- P6+
fucomip_1 = "ff:DFE8r", -- P6+
fucomip_2 = "Fff:DFE8R", -- P6+
fcomi_1 = "ff:DBF0r", -- P6+
fcomi_2 = "Fff:DBF0R", -- P6+
fcomip_1 = "ff:DFF0r", -- P6+
fcomip_2 = "Fff:DFF0R", -- P6+
fucompp_0 = "DAE9",
fcompp_0 = "DED9",
fldenv_1 = "x.:D94m",
fnstenv_1 = "x.:D96m",
fstenv_1 = "x.:9BD96m",
fldcw_1 = "xw:nD95m",
fstcw_1 = "xw:n9BD97m",
fnstcw_1 = "xw:nD97m",
fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m",
fnstsw_1 = "Rw:nDFE0|xw:nDD7m",
fclex_0 = "9BDBE2",
fnclex_0 = "DBE2",
fnop_0 = "D9D0",
-- D9D1-D9DF: unassigned
fchs_0 = "D9E0",
fabs_0 = "D9E1",
-- D9E2: unassigned
-- D9E3: unassigned
ftst_0 = "D9E4",
fxam_0 = "D9E5",
-- D9E6: unassigned
-- D9E7: unassigned
fld1_0 = "D9E8",
fldl2t_0 = "D9E9",
fldl2e_0 = "D9EA",
fldpi_0 = "D9EB",
fldlg2_0 = "D9EC",
fldln2_0 = "D9ED",
fldz_0 = "D9EE",
-- D9EF: unassigned
f2xm1_0 = "D9F0",
fyl2x_0 = "D9F1",
fptan_0 = "D9F2",
fpatan_0 = "D9F3",
fxtract_0 = "D9F4",
fprem1_0 = "D9F5",
fdecstp_0 = "D9F6",
fincstp_0 = "D9F7",
fprem_0 = "D9F8",
fyl2xp1_0 = "D9F9",
fsqrt_0 = "D9FA",
fsincos_0 = "D9FB",
frndint_0 = "D9FC",
fscale_0 = "D9FD",
fsin_0 = "D9FE",
fcos_0 = "D9FF",
-- SSE, SSE2
andnpd_2 = "rmo:660F55rM",
andnps_2 = "rmo:0F55rM",
andpd_2 = "rmo:660F54rM",
andps_2 = "rmo:0F54rM",
clflush_1 = "x.:0FAE7m",
cmppd_3 = "rmio:660FC2rMU",
cmpps_3 = "rmio:0FC2rMU",
cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:",
cmpss_3 = "rrio:F30FC2rMU|rxi/od:",
comisd_2 = "rro:660F2FrM|rx/oq:",
comiss_2 = "rro:0F2FrM|rx/od:",
cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:",
cvtdq2ps_2 = "rmo:0F5BrM",
cvtpd2dq_2 = "rmo:F20FE6rM",
cvtpd2ps_2 = "rmo:660F5ArM",
cvtpi2pd_2 = "rx/oq:660F2ArM",
cvtpi2ps_2 = "rx/oq:0F2ArM",
cvtps2dq_2 = "rmo:660F5BrM",
cvtps2pd_2 = "rro:0F5ArM|rx/oq:",
cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:",
cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:",
cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM",
cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM",
cvtss2sd_2 = "rro:F30F5ArM|rx/od:",
cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:",
cvttpd2dq_2 = "rmo:660FE6rM",
cvttps2dq_2 = "rmo:F30F5BrM",
cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:",
cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:",
fxsave_1 = "x.:0FAE0m",
fxrstor_1 = "x.:0FAE1m",
ldmxcsr_1 = "xd:0FAE2m",
lfence_0 = "0FAEE8",
maskmovdqu_2 = "rro:660FF7rM",
mfence_0 = "0FAEF0",
movapd_2 = "rmo:660F28rM|mro:660F29Rm",
movaps_2 = "rmo:0F28rM|mro:0F29Rm",
movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:",
movdqa_2 = "rmo:660F6FrM|mro:660F7FRm",
movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm",
movhlps_2 = "rro:0F12rM",
movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm",
movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm",
movlhps_2 = "rro:0F16rM",
movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm",
movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm",
movmskpd_2 = "rr/do:660F50rM",
movmskps_2 = "rr/do:0F50rM",
movntdq_2 = "xro:660FE7Rm",
movnti_2 = "xrqd:0FC3Rm",
movntpd_2 = "xro:660F2BRm",
movntps_2 = "xro:0F2BRm",
movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm",
movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm",
movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm",
movupd_2 = "rmo:660F10rM|mro:660F11Rm",
movups_2 = "rmo:0F10rM|mro:0F11Rm",
orpd_2 = "rmo:660F56rM",
orps_2 = "rmo:0F56rM",
pause_0 = "F390",
pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only.
pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:",
pmovmskb_2 = "rr/do:660FD7rM",
prefetchnta_1 = "xb:n0F180m",
prefetcht0_1 = "xb:n0F181m",
prefetcht1_1 = "xb:n0F182m",
prefetcht2_1 = "xb:n0F183m",
pshufd_3 = "rmio:660F70rMU",
pshufhw_3 = "rmio:F30F70rMU",
pshuflw_3 = "rmio:F20F70rMU",
pslld_2 = "rmo:660FF2rM|rio:660F726mU",
pslldq_2 = "rio:660F737mU",
psllq_2 = "rmo:660FF3rM|rio:660F736mU",
psllw_2 = "rmo:660FF1rM|rio:660F716mU",
psrad_2 = "rmo:660FE2rM|rio:660F724mU",
psraw_2 = "rmo:660FE1rM|rio:660F714mU",
psrld_2 = "rmo:660FD2rM|rio:660F722mU",
psrldq_2 = "rio:660F733mU",
psrlq_2 = "rmo:660FD3rM|rio:660F732mU",
psrlw_2 = "rmo:660FD1rM|rio:660F712mU",
rcpps_2 = "rmo:0F53rM",
rcpss_2 = "rro:F30F53rM|rx/od:",
rsqrtps_2 = "rmo:0F52rM",
rsqrtss_2 = "rmo:F30F52rM",
sfence_0 = "0FAEF8",
shufpd_3 = "rmio:660FC6rMU",
shufps_3 = "rmio:0FC6rMU",
stmxcsr_1 = "xd:0FAE3m",
ucomisd_2 = "rro:660F2ErM|rx/oq:",
ucomiss_2 = "rro:0F2ErM|rx/od:",
unpckhpd_2 = "rmo:660F15rM",
unpckhps_2 = "rmo:0F15rM",
unpcklpd_2 = "rmo:660F14rM",
unpcklps_2 = "rmo:0F14rM",
xorpd_2 = "rmo:660F57rM",
xorps_2 = "rmo:0F57rM",
-- SSE3 ops
fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m",
addsubpd_2 = "rmo:660FD0rM",
addsubps_2 = "rmo:F20FD0rM",
haddpd_2 = "rmo:660F7CrM",
haddps_2 = "rmo:F20F7CrM",
hsubpd_2 = "rmo:660F7DrM",
hsubps_2 = "rmo:F20F7DrM",
lddqu_2 = "rxo:F20FF0rM",
movddup_2 = "rmo:F20F12rM",
movshdup_2 = "rmo:F30F16rM",
movsldup_2 = "rmo:F30F12rM",
-- SSSE3 ops
pabsb_2 = "rmo:660F381CrM",
pabsd_2 = "rmo:660F381ErM",
pabsw_2 = "rmo:660F381DrM",
palignr_3 = "rmio:660F3A0FrMU",
phaddd_2 = "rmo:660F3802rM",
phaddsw_2 = "rmo:660F3803rM",
phaddw_2 = "rmo:660F3801rM",
phsubd_2 = "rmo:660F3806rM",
phsubsw_2 = "rmo:660F3807rM",
phsubw_2 = "rmo:660F3805rM",
pmaddubsw_2 = "rmo:660F3804rM",
pmulhrsw_2 = "rmo:660F380BrM",
pshufb_2 = "rmo:660F3800rM",
psignb_2 = "rmo:660F3808rM",
psignd_2 = "rmo:660F380ArM",
psignw_2 = "rmo:660F3809rM",
-- SSE4.1 ops
blendpd_3 = "rmio:660F3A0DrMU",
blendps_3 = "rmio:660F3A0CrMU",
blendvpd_3 = "rmRo:660F3815rM",
blendvps_3 = "rmRo:660F3814rM",
dppd_3 = "rmio:660F3A41rMU",
dpps_3 = "rmio:660F3A40rMU",
extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU",
insertps_3 = "rrio:660F3A41rMU|rxi/od:",
movntdqa_2 = "rxo:660F382ArM",
mpsadbw_3 = "rmio:660F3A42rMU",
packusdw_2 = "rmo:660F382BrM",
pblendvb_3 = "rmRo:660F3810rM",
pblendw_3 = "rmio:660F3A0ErMU",
pcmpeqq_2 = "rmo:660F3829rM",
pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:",
pextrd_3 = "mri/do:660F3A16RmU",
pextrq_3 = "mri/qo:660F3A16RmU",
-- pextrw is SSE2, mem operand is SSE4.1 only
phminposuw_2 = "rmo:660F3841rM",
pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:",
pinsrd_3 = "rmi/od:660F3A22rMU",
pinsrq_3 = "rmi/oq:660F3A22rXMU",
pmaxsb_2 = "rmo:660F383CrM",
pmaxsd_2 = "rmo:660F383DrM",
pmaxud_2 = "rmo:660F383FrM",
pmaxuw_2 = "rmo:660F383ErM",
pminsb_2 = "rmo:660F3838rM",
pminsd_2 = "rmo:660F3839rM",
pminud_2 = "rmo:660F383BrM",
pminuw_2 = "rmo:660F383ArM",
pmovsxbd_2 = "rro:660F3821rM|rx/od:",
pmovsxbq_2 = "rro:660F3822rM|rx/ow:",
pmovsxbw_2 = "rro:660F3820rM|rx/oq:",
pmovsxdq_2 = "rro:660F3825rM|rx/oq:",
pmovsxwd_2 = "rro:660F3823rM|rx/oq:",
pmovsxwq_2 = "rro:660F3824rM|rx/od:",
pmovzxbd_2 = "rro:660F3831rM|rx/od:",
pmovzxbq_2 = "rro:660F3832rM|rx/ow:",
pmovzxbw_2 = "rro:660F3830rM|rx/oq:",
pmovzxdq_2 = "rro:660F3835rM|rx/oq:",
pmovzxwd_2 = "rro:660F3833rM|rx/oq:",
pmovzxwq_2 = "rro:660F3834rM|rx/od:",
pmuldq_2 = "rmo:660F3828rM",
pmulld_2 = "rmo:660F3840rM",
ptest_2 = "rmo:660F3817rM",
roundpd_3 = "rmio:660F3A09rMU",
roundps_3 = "rmio:660F3A08rMU",
roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:",
roundss_3 = "rrio:660F3A0ArMU|rxi/od:",
-- SSE4.2 ops
crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:",
pcmpestri_3 = "rmio:660F3A61rMU",
pcmpestrm_3 = "rmio:660F3A60rMU",
pcmpgtq_2 = "rmo:660F3837rM",
pcmpistri_3 = "rmio:660F3A63rMU",
pcmpistrm_3 = "rmio:660F3A62rMU",
popcnt_2 = "rmqdw:F30FB8rM",
-- SSE4a
extrq_2 = "rro:660F79rM",
extrq_3 = "riio:660F780mUU",
insertq_2 = "rro:F20F79rM",
insertq_4 = "rriio:F20F78rMUU",
lzcnt_2 = "rmqdw:F30FBDrM",
movntsd_2 = "xr/qo:nF20F2BRm",
movntss_2 = "xr/do:F30F2BRm",
-- popcnt is also in SSE4.2
-- AES-NI
aesdec_2 = "rmo:660F38DErM",
aesdeclast_2 = "rmo:660F38DFrM",
aesenc_2 = "rmo:660F38DCrM",
aesenclast_2 = "rmo:660F38DDrM",
aesimc_2 = "rmo:660F38DBrM",
aeskeygenassist_3 = "rmio:660F3ADFrMU",
pclmulqdq_3 = "rmio:660F3A44rMU",
-- AVX FP ops
vaddsubpd_3 = "rrmoy:660FVD0rM",
vaddsubps_3 = "rrmoy:F20FVD0rM",
vandpd_3 = "rrmoy:660FV54rM",
vandps_3 = "rrmoy:0FV54rM",
vandnpd_3 = "rrmoy:660FV55rM",
vandnps_3 = "rrmoy:0FV55rM",
vblendpd_4 = "rrmioy:660F3AV0DrMU",
vblendps_4 = "rrmioy:660F3AV0CrMU",
vblendvpd_4 = "rrmroy:660F3AV4BrMs",
vblendvps_4 = "rrmroy:660F3AV4ArMs",
vbroadcastf128_2 = "rx/yo:660F38u1ArM",
vcmppd_4 = "rrmioy:660FVC2rMU",
vcmpps_4 = "rrmioy:0FVC2rMU",
vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:",
vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:",
vcomisd_2 = "rro:660Fu2FrM|rx/oq:",
vcomiss_2 = "rro:0Fu2FrM|rx/od:",
vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:",
vcvtdq2ps_2 = "rmoy:0Fu5BrM",
vcvtpd2dq_2 = "rmoy:F20FuE6rM",
vcvtpd2ps_2 = "rmoy:660Fu5ArM",
vcvtps2dq_2 = "rmoy:660Fu5BrM",
vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:",
vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:",
vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:",
vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM",
vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM",
vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:",
vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:",
vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM",
vcvttps2dq_2 = "rmoy:F30Fu5BrM",
vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:",
vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:",
vdppd_4 = "rrmio:660F3AV41rMU",
vdpps_4 = "rrmioy:660F3AV40rMU",
vextractf128_3 = "mri/oy:660F3AuL19RmU",
vextractps_3 = "mri/do:660F3Au17RmU",
vhaddpd_3 = "rrmoy:660FV7CrM",
vhaddps_3 = "rrmoy:F20FV7CrM",
vhsubpd_3 = "rrmoy:660FV7DrM",
vhsubps_3 = "rrmoy:F20FV7DrM",
vinsertf128_4 = "rrmi/yyo:660F3AV18rMU",
vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:",
vldmxcsr_1 = "xd:0FuAE2m",
vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm",
vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm",
vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm",
vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm",
vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:",
vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm",
vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:",
vmovhlps_3 = "rrro:0FV12rM",
vmovhpd_2 = "xr/qo:660Fu17Rm",
vmovhpd_3 = "rrx/ooq:660FV16rM",
vmovhps_2 = "xr/qo:0Fu17Rm",
vmovhps_3 = "rrx/ooq:0FV16rM",
vmovlhps_3 = "rrro:0FV16rM",
vmovlpd_2 = "xr/qo:660Fu13Rm",
vmovlpd_3 = "rrx/ooq:660FV12rM",
vmovlps_2 = "xr/qo:0Fu13Rm",
vmovlps_3 = "rrx/ooq:0FV12rM",
vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM",
vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM",
vmovntpd_2 = "xroy:660Fu2BRm",
vmovntps_2 = "xroy:0Fu2BRm",
vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm",
vmovsd_3 = "rrro:F20FV10rM",
vmovshdup_2 = "rmoy:F30Fu16rM",
vmovsldup_2 = "rmoy:F30Fu12rM",
vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm",
vmovss_3 = "rrro:F30FV10rM",
vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm",
vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm",
vorpd_3 = "rrmoy:660FV56rM",
vorps_3 = "rrmoy:0FV56rM",
vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU",
vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU",
vperm2f128_4 = "rrmiy:660F3AV06rMU",
vptestpd_2 = "rmoy:660F38u0FrM",
vptestps_2 = "rmoy:660F38u0ErM",
vrcpps_2 = "rmoy:0Fu53rM",
vrcpss_3 = "rrro:F30FV53rM|rrx/ood:",
vrsqrtps_2 = "rmoy:0Fu52rM",
vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:",
vroundpd_3 = "rmioy:660F3AV09rMU",
vroundps_3 = "rmioy:660F3AV08rMU",
vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:",
vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:",
vshufpd_4 = "rrmioy:660FVC6rMU",
vshufps_4 = "rrmioy:0FVC6rMU",
vsqrtps_2 = "rmoy:0Fu51rM",
vsqrtss_2 = "rro:F30Fu51rM|rx/od:",
vsqrtpd_2 = "rmoy:660Fu51rM",
vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:",
vstmxcsr_1 = "xd:0FuAE3m",
vucomisd_2 = "rro:660Fu2ErM|rx/oq:",
vucomiss_2 = "rro:0Fu2ErM|rx/od:",
vunpckhpd_3 = "rrmoy:660FV15rM",
vunpckhps_3 = "rrmoy:0FV15rM",
vunpcklpd_3 = "rrmoy:660FV14rM",
vunpcklps_3 = "rrmoy:0FV14rM",
vxorpd_3 = "rrmoy:660FV57rM",
vxorps_3 = "rrmoy:0FV57rM",
vzeroall_0 = "0FuL77",
vzeroupper_0 = "0Fu77",
-- AVX2 FP ops
vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:",
vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:",
-- *vgather* (!vsib)
vpermpd_3 = "rmiy:660F3AuX01rMU",
vpermps_3 = "rrmy:660F38V16rM",
-- AVX, AVX2 integer ops
-- In general, xmm requires AVX, ymm requires AVX2.
vaesdec_3 = "rrmo:660F38VDErM",
vaesdeclast_3 = "rrmo:660F38VDFrM",
vaesenc_3 = "rrmo:660F38VDCrM",
vaesenclast_3 = "rrmo:660F38VDDrM",
vaesimc_2 = "rmo:660F38uDBrM",
vaeskeygenassist_3 = "rmio:660F3AuDFrMU",
vlddqu_2 = "rxoy:F20FuF0rM",
vmaskmovdqu_2 = "rro:660FuF7rM",
vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm",
vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm",
vmovntdq_2 = "xroy:660FuE7Rm",
vmovntdqa_2 = "rxoy:660F38u2ArM",
vmpsadbw_4 = "rrmioy:660F3AV42rMU",
vpabsb_2 = "rmoy:660F38u1CrM",
vpabsd_2 = "rmoy:660F38u1ErM",
vpabsw_2 = "rmoy:660F38u1DrM",
vpackusdw_3 = "rrmoy:660F38V2BrM",
vpalignr_4 = "rrmioy:660F3AV0FrMU",
vpblendvb_4 = "rrmroy:660F3AV4CrMs",
vpblendw_4 = "rrmioy:660F3AV0ErMU",
vpclmulqdq_4 = "rrmio:660F3AV44rMU",
vpcmpeqq_3 = "rrmoy:660F38V29rM",
vpcmpestri_3 = "rmio:660F3Au61rMU",
vpcmpestrm_3 = "rmio:660F3Au60rMU",
vpcmpgtq_3 = "rrmoy:660F38V37rM",
vpcmpistri_3 = "rmio:660F3Au63rMU",
vpcmpistrm_3 = "rmio:660F3Au62rMU",
vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:",
vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU",
vpextrd_3 = "mri/do:660F3Au16RmU",
vpextrq_3 = "mri/qo:660F3Au16RmU",
vphaddw_3 = "rrmoy:660F38V01rM",
vphaddd_3 = "rrmoy:660F38V02rM",
vphaddsw_3 = "rrmoy:660F38V03rM",
vphminposuw_2 = "rmo:660F38u41rM",
vphsubw_3 = "rrmoy:660F38V05rM",
vphsubd_3 = "rrmoy:660F38V06rM",
vphsubsw_3 = "rrmoy:660F38V07rM",
vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:",
vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:",
vpinsrd_4 = "rrmi/ood:660F3AV22rMU",
vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU",
vpmaddubsw_3 = "rrmoy:660F38V04rM",
vpmaxsb_3 = "rrmoy:660F38V3CrM",
vpmaxsd_3 = "rrmoy:660F38V3DrM",
vpmaxuw_3 = "rrmoy:660F38V3ErM",
vpmaxud_3 = "rrmoy:660F38V3FrM",
vpminsb_3 = "rrmoy:660F38V38rM",
vpminsd_3 = "rrmoy:660F38V39rM",
vpminuw_3 = "rrmoy:660F38V3ArM",
vpminud_3 = "rrmoy:660F38V3BrM",
vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM",
vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:",
vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:",
vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:",
vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:",
vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:",
vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:",
vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:",
vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:",
vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:",
vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:",
vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:",
vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:",
vpmuldq_3 = "rrmoy:660F38V28rM",
vpmulhrsw_3 = "rrmoy:660F38V0BrM",
vpmulld_3 = "rrmoy:660F38V40rM",
vpshufb_3 = "rrmoy:660F38V00rM",
vpshufd_3 = "rmioy:660Fu70rMU",
vpshufhw_3 = "rmioy:F30Fu70rMU",
vpshuflw_3 = "rmioy:F20Fu70rMU",
vpsignb_3 = "rrmoy:660F38V08rM",
vpsignw_3 = "rrmoy:660F38V09rM",
vpsignd_3 = "rrmoy:660F38V0ArM",
vpslldq_3 = "rrioy:660Fv737mU",
vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU",
vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU",
vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU",
vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU",
vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU",
vpsrldq_3 = "rrioy:660Fv733mU",
vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU",
vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU",
vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU",
vptest_2 = "rmoy:660F38u17rM",
-- AVX2 integer ops
vbroadcasti128_2 = "rx/yo:660F38u5ArM",
vinserti128_4 = "rrmi/yyo:660F3AV38rMU",
vextracti128_3 = "mri/oy:660F3AuL39RmU",
vpblendd_4 = "rrmioy:660F3AV02rMU",
vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:",
vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:",
vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:",
vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:",
vpermd_3 = "rrmy:660F38V36rM",
vpermq_3 = "rmiy:660F3AuX00rMU",
-- *vpgather* (!vsib)
vperm2i128_4 = "rrmiy:660F3AV46rMU",
vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm",
vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm",
vpsllvd_3 = "rrmoy:660F38V47rM",
vpsllvq_3 = "rrmoy:660F38VX47rM",
vpsravd_3 = "rrmoy:660F38V46rM",
vpsrlvd_3 = "rrmoy:660F38V45rM",
vpsrlvq_3 = "rrmoy:660F38VX45rM",
-- Intel ADX
adcx_2 = "rmqd:660F38F6rM",
adox_2 = "rmqd:F30F38F6rM",
}
------------------------------------------------------------------------------
-- Arithmetic ops.
for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3,
["and"] = 4, sub = 5, xor = 6, cmp = 7 } do
local n8 = shl(n, 3)
map_op[name.."_2"] = format(
"mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi",
1+n8, 3+n8, n, n, 5+n8, n)
end
-- Shift ops.
for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3,
shl = 4, shr = 5, sar = 7, sal = 4 } do
map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n)
end
-- Conditional ops.
for cc,n in pairs(map_cc) do
map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X
map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n)
map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+
end
-- FP arithmetic ops.
for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3,
sub = 4, subr = 5, div = 6, divr = 7 } do
local nc = 0xc0 + shl(n, 3)
local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8))
local fn = "f"..name
map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n)
if n == 2 or n == 3 then
map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n)
else
map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n)
map_op[fn.."p_1"] = format("ff:DE%02Xr", nr)
map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr)
end
map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n)
end
-- FP conditional moves.
for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do
local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6)
map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+
map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+
end
-- SSE / AVX FP arithmetic ops.
for name,n in pairs{ sqrt = 1, add = 8, mul = 9,
sub = 12, min = 13, div = 14, max = 15 } do
map_op[name.."ps_2"] = format("rmo:0F5%XrM", n)
map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n)
map_op[name.."pd_2"] = format("rmo:660F5%XrM", n)
map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n)
if n ~= 1 then
map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n)
map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n)
map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n)
map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n)
end
end
-- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf).
for name,n in pairs{
paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4,
paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B,
packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC,
paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0,
pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76,
pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66,
pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE,
pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA,
pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5,
pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8,
psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8,
psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9,
punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A,
punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61,
punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF
} do
map_op[name.."_2"] = format("rmo:660F%02XrM", n)
map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n)
end
------------------------------------------------------------------------------
local map_vexarg = { u = false, v = 1, V = 2 }
-- Process pattern string.
local function dopattern(pat, args, sz, op, needrex)
local digit, addin, vex
local opcode = 0
local szov = sz
local narg = 1
local rex = 0
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 6 positions.
if secpos+6 > maxsecpos then wflush() end
-- Process each character.
for c in gmatch(pat.."|", ".") do
if match(c, "%x") then -- Hex digit.
digit = byte(c) - 48
if digit > 48 then digit = digit - 39
elseif digit > 16 then digit = digit - 7 end
opcode = opcode*16 + digit
addin = nil
elseif c == "n" then -- Disable operand size mods for opcode.
szov = nil
elseif c == "X" then -- Force REX.W.
rex = 8
elseif c == "L" then -- Force VEX.L.
vex.l = true
elseif c == "r" then -- Merge 1st operand regno. into opcode.
addin = args[1]; opcode = opcode + (addin.reg % 8)
if narg < 2 then narg = 2 end
elseif c == "R" then -- Merge 2nd operand regno. into opcode.
addin = args[2]; opcode = opcode + (addin.reg % 8)
narg = 3
elseif c == "m" or c == "M" then -- Encode ModRM/SIB.
local s
if addin then
s = addin.reg
opcode = opcode - band(s, 7) -- Undo regno opcode merge.
else
s = band(opcode, 15) -- Undo last digit.
opcode = shr(opcode, 4)
end
local nn = c == "m" and 1 or 2
local t = args[nn]
if narg <= nn then narg = nn + 1 end
if szov == "q" and rex == 0 then rex = rex + 8 end
if t.reg and t.reg > 7 then rex = rex + 1 end
if t.xreg and t.xreg > 7 then rex = rex + 2 end
if s > 7 then rex = rex + 4 end
if needrex then rex = rex + 16 end
local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg)
opcode = nil
local imark = sub(pat, -1) -- Force a mark (ugly).
-- Put ModRM/SIB with regno/last digit as spare.
wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk)
addin = nil
elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix
local b = band(opcode, 255); opcode = shr(opcode, 8)
local m = 1
if b == 0x38 then m = 2
elseif b == 0x3a then m = 3 end
if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end
if b ~= 0x0f then
werror("expected `0F', `0F38', or `0F3A' to precede `"..c..
"' in pattern `"..pat.."' for `"..op.."'")
end
local v = map_vexarg[c]
if v then v = remove(args, v) end
b = band(opcode, 255)
local p = 0
if b == 0x66 then p = 1
elseif b == 0xf3 then p = 2
elseif b == 0xf2 then p = 3 end
if p ~= 0 then opcode = shr(opcode, 8) end
if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end
vex = { m = m, p = p, v = v }
else
if opcode then -- Flush opcode.
if szov == "q" and rex == 0 then rex = rex + 8 end
if needrex then rex = rex + 16 end
if addin and addin.reg == -1 then
local psz, sk = wputop(szov, opcode - 7, rex, vex, true)
wvreg("opcode", addin.vreg, psz, sk)
else
if addin and addin.reg > 7 then rex = rex + 1 end
wputop(szov, opcode, rex, vex)
end
opcode = nil
end
if c == "|" then break end
if c == "o" then -- Offset (pure 32 bit displacement).
wputdarg(args[1].disp); if narg < 2 then narg = 2 end
elseif c == "O" then
wputdarg(args[2].disp); narg = 3
else
-- Anything else is an immediate operand.
local a = args[narg]
narg = narg + 1
local mode, imm = a.mode, a.imm
if mode == "iJ" and not match("iIJ", c) then
werror("bad operand size for label")
end
if c == "S" then
wputsbarg(imm)
elseif c == "U" then
wputbarg(imm)
elseif c == "W" then
wputwarg(imm)
elseif c == "i" or c == "I" then
if mode == "iJ" then
wputlabel("IMM_", imm, 1)
elseif mode == "iI" and c == "I" then
waction(sz == "w" and "IMM_WB" or "IMM_DB", imm)
else
wputszarg(sz, imm)
end
elseif c == "J" then
if mode == "iPJ" then
waction("REL_A", imm) -- !x64 (secpos)
else
wputlabel("REL_", imm, 2)
end
elseif c == "s" then
local reg = a.reg
if reg < 0 then
wputb(0)
wvreg("imm.hi", a.vreg)
else
wputb(shl(reg, 4))
end
else
werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'")
end
end
end
end
end
------------------------------------------------------------------------------
-- Mapping of operand modes to short names. Suppress output with '#'.
local map_modename = {
r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm",
f = "stx", F = "st0", J = "lbl", ["1"] = "1",
I = "#", S = "#", O = "#",
}
-- Return a table/string showing all possible operand modes.
local function templatehelp(template, nparams)
if nparams == 0 then return "" end
local t = {}
for tm in gmatch(template, "[^%|]+") do
local s = map_modename[sub(tm, 1, 1)]
s = s..gsub(sub(tm, 2, nparams), ".", function(c)
return ", "..map_modename[c]
end)
if not match(s, "#") then t[#t+1] = s end
end
return t
end
-- Match operand modes against mode match part of template.
local function matchtm(tm, args)
for i=1,#args do
if not match(args[i].mode, sub(tm, i, i)) then return end
end
return true
end
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return templatehelp(template, nparams) end
local args = {}
-- Zero-operand opcodes have no match part.
if #params == 0 then
dopattern(template, args, "d", params.op, nil)
return
end
-- Determine common operand size (coerce undefined size) or flag as mixed.
local sz, szmix, needrex
for i,p in ipairs(params) do
args[i] = parseoperand(p)
local nsz = args[i].opsize
if nsz then
if sz and sz ~= nsz then szmix = true else sz = nsz end
end
local nrex = args[i].needrex
if nrex ~= nil then
if needrex == nil then
needrex = nrex
elseif needrex ~= nrex then
werror("bad mix of byte-addressable registers")
end
end
end
-- Try all match:pattern pairs (separated by '|').
local gotmatch, lastpat
for tm in gmatch(template, "[^%|]+") do
-- Split off size match (starts after mode match) and pattern string.
local szm, pat = match(tm, "^(.-):(.*)$", #args+1)
if pat == "" then pat = lastpat else lastpat = pat end
if matchtm(tm, args) then
local prefix = sub(szm, 1, 1)
if prefix == "/" then -- Exactly match leading operand sizes.
for i = #szm,1,-1 do
if i == 1 then
dopattern(pat, args, sz, params.op, needrex) -- Process pattern.
return
elseif args[i-1].opsize ~= sub(szm, i, i) then
break
end
end
else -- Match common operand size.
local szp = sz
if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes.
if prefix == "1" then szp = args[1].opsize; szmix = nil
elseif prefix == "2" then szp = args[2].opsize; szmix = nil end
if not szmix and (prefix == "." or match(szm, szp or "#")) then
dopattern(pat, args, szp, params.op, needrex) -- Process pattern.
return
end
end
gotmatch = true
end
end
local msg = "bad operand mode"
if gotmatch then
if szmix then
msg = "mixed operand size"
else
msg = sz and "bad operand size" or "missing operand size"
end
end
werror(msg.." in `"..opmodestr(params.op, args).."'")
end
------------------------------------------------------------------------------
-- x64-specific opcode for 64 bit immediates and displacements.
if x64 then
function map_op.mov64_2(params)
if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end
if secpos+2 > maxsecpos then wflush() end
local opcode, op64, sz, rex, vreg
local op64 = match(params[1], "^%[%s*(.-)%s*%]$")
if op64 then
local a = parseoperand(params[2])
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa3
else
op64 = match(params[2], "^%[%s*(.-)%s*%]$")
local a = parseoperand(params[1])
if op64 then
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa1
else
if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then
werror("bad operand mode")
end
op64 = params[2]
if a.reg == -1 then
vreg = a.vreg
opcode = 0xb8
else
opcode = 0xb8 + band(a.reg, 7)
end
rex = a.reg > 7 and 9 or 8
end
end
local psz, sk = wputop(sz, opcode, rex, nil, vreg)
wvreg("opcode", vreg, psz, sk)
waction("IMM_D", format("(unsigned int)(%s)", op64))
waction("IMM_D", format("(unsigned int)((%s)>>32)", op64))
end
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
local function op_data(params)
if not params then return "imm..." end
local sz = sub(params.op, 2, 2)
if sz == "a" then sz = addrsize end
for _,p in ipairs(params) do
local a = parseoperand(p)
if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then
werror("bad mode or size in `"..p.."'")
end
if a.mode == "iJ" then
wputlabel("IMM_", a.imm, 1)
else
wputszarg(sz, a.imm)
end
if secpos+2 > maxsecpos then wflush() end
end
end
map_op[".byte_*"] = op_data
map_op[".sbyte_*"] = op_data
map_op[".word_*"] = op_data
map_op[".dword_*"] = op_data
map_op[".aword_*"] = op_data
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_2"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end
if secpos+2 > maxsecpos then wflush() end
local a = parseoperand(params[1])
local mode, imm = a.mode, a.imm
if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then
-- Local label (1: ... 9:) or global label (->global:).
waction("LABEL_LG", nil, 1)
wputxb(imm)
elseif mode == "iJ" then
-- PC label (=>pcexpr:).
waction("LABEL_PC", imm)
else
werror("bad label definition")
end
-- SETLABEL must immediately follow LABEL_LG/LABEL_PC.
local addr = params[2]
if addr then
local a = parseoperand(addr)
if a.mode == "iPJ" then
waction("SETLABEL", a.imm)
else
werror("bad label assignment")
end
end
end
map_op[".label_1"] = map_op[".label_2"]
------------------------------------------------------------------------------
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]]
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", nil, 1)
wputxb(align-1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
-- Spacing pseudo-opcode.
map_op[".space_2"] = function(params)
if not params then return "num [, filler]" end
if secpos+1 > maxsecpos then wflush() end
waction("SPACE", params[1])
local fill = params[2]
if fill then
fill = tonumber(fill)
if not fill or fill < 0 or fill > 255 then werror("bad filler") end
end
wputxb(fill or 0)
end
map_op[".space_1"] = map_op[".space_2"]
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
if reg and not map_reg_valid_base[reg] then
werror("bad base register `"..(map_reg_rev[reg] or reg).."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg and map_reg_rev[tp.reg] or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION")
wputxb(num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpregs(out)
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| mit |
sum2012/mame | scripts/src/main.lua | 1 | 10848 | -- license:BSD-3-Clause
-- copyright-holders:MAMEdev Team
---------------------------------------------------------------------------
--
-- main.lua
--
-- Rules for building main binary
--
---------------------------------------------------------------------------
function mainProject(_target, _subtarget)
if (_OPTIONS["SOURCES"] == nil) then
if (_target == _subtarget) then
project (_target)
else
if (_subtarget=="mess") then
project (_subtarget)
else
project (_target .. _subtarget)
end
end
else
project (_subtarget)
end
uuid (os.uuid(_target .."_" .. _subtarget))
kind "ConsoleApp"
configuration { "android*" }
targetprefix "lib"
targetname "main"
targetextension ".so"
linkoptions {
"-shared",
"-Wl,-soname,libmain.so"
}
links {
"EGL",
"GLESv1_CM",
"GLESv2",
"SDL2",
}
configuration { "pnacl" }
kind "ConsoleApp"
targetextension ".pexe"
links {
"ppapi",
"ppapi_gles2",
"pthread",
}
configuration { }
addprojectflags()
flags {
"NoManifest",
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SYMBOLS"] then
configuration { "mingw*" }
postbuildcommands {
"$(SILENT) echo Dumping symbols.",
"$(SILENT) objdump --section=.text --line-numbers --syms --demangle $(TARGET) >$(subst .exe,.sym,$(TARGET))"
}
end
configuration { "vs*" }
flags {
"Unicode",
}
configuration { "x64", "Release" }
targetsuffix "64"
if _OPTIONS["PROFILE"] then
targetsuffix "64p"
end
configuration { "x64", "Debug" }
targetsuffix "64d"
if _OPTIONS["PROFILE"] then
targetsuffix "64dp"
end
configuration { "x32", "Release" }
targetsuffix ""
if _OPTIONS["PROFILE"] then
targetsuffix "p"
end
configuration { "x32", "Debug" }
targetsuffix "d"
if _OPTIONS["PROFILE"] then
targetsuffix "dp"
end
configuration { "Native", "Release" }
targetsuffix ""
if _OPTIONS["PROFILE"] then
targetsuffix "p"
end
configuration { "Native", "Debug" }
targetsuffix "d"
if _OPTIONS["PROFILE"] then
targetsuffix "dp"
end
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { "rpi" }
targetextension ""
configuration { "asmjs" }
targetextension ".bc"
if os.getenv("EMSCRIPTEN") then
local emccopts = ""
emccopts = emccopts .. " -O3"
emccopts = emccopts .. " -s USE_SDL=2"
emccopts = emccopts .. " -s USE_SDL_TTF=2"
emccopts = emccopts .. " --memory-init-file 0"
emccopts = emccopts .. " -s ALLOW_MEMORY_GROWTH=0"
emccopts = emccopts .. " -s TOTAL_MEMORY=268435456"
emccopts = emccopts .. " -s DISABLE_EXCEPTION_CATCHING=2"
emccopts = emccopts .. " -s EXCEPTION_CATCHING_WHITELIST='[\"__ZN15running_machine17start_all_devicesEv\",\"__ZN12cli_frontend7executeEiPPc\"]'"
emccopts = emccopts .. " -s EXPORTED_FUNCTIONS=\"['_main', '_malloc', '__Z14js_get_machinev', '__Z9js_get_uiv', '__Z12js_get_soundv', '__ZN10ui_manager12set_show_fpsEb', '__ZNK10ui_manager8show_fpsEv', '__ZN13sound_manager4muteEbh', '_SDL_PauseAudio']\""
emccopts = emccopts .. " --pre-js " .. _MAKE.esc(MAME_DIR) .. "src/osd/modules/sound/js_sound.js"
emccopts = emccopts .. " --post-js " .. _MAKE.esc(MAME_DIR) .. "src/osd/sdl/emscripten_post.js"
emccopts = emccopts .. " --embed-file " .. _MAKE.esc(MAME_DIR) .. "bgfx/chains@bgfx/chains"
emccopts = emccopts .. " --embed-file " .. _MAKE.esc(MAME_DIR) .. "bgfx/effects@bgfx/effects"
emccopts = emccopts .. " --embed-file " .. _MAKE.esc(MAME_DIR) .. "bgfx/shaders/gles@bgfx/shaders/gles"
emccopts = emccopts .. " --embed-file " .. _MAKE.esc(MAME_DIR) .. "artwork/shadow-mask.png@artwork/shadow-mask.png"
postbuildcommands {
os.getenv("EMSCRIPTEN") .. "/emcc " .. emccopts .. " $(TARGET) -o " .. _MAKE.esc(MAME_DIR) .. _OPTIONS["target"] .. _OPTIONS["subtarget"] .. ".js",
}
end
configuration { }
if _OPTIONS["targetos"]=="android" then
includedirs {
MAME_DIR .. "3rdparty/SDL2/include",
}
files {
MAME_DIR .. "3rdparty/SDL2/src/main/android/SDL_android_main.c",
}
targetsuffix ""
if _OPTIONS["SEPARATE_BIN"]~="1" then
if _OPTIONS["PLATFORM"]=="arm" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/armeabi-v7a")
end
if _OPTIONS["PLATFORM"]=="arm64" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/arm64-v8a")
end
if _OPTIONS["PLATFORM"]=="mips" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/mips")
end
if _OPTIONS["PLATFORM"]=="mips64" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/mips64")
end
if _OPTIONS["PLATFORM"]=="x86" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/x86")
end
if _OPTIONS["PLATFORM"]=="x64" then
targetdir(MAME_DIR .. "android-project/app/src/main/libs/x86_64")
end
end
else
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
end
findfunction("linkProjects_" .. _OPTIONS["target"] .. "_" .. _OPTIONS["subtarget"])(_OPTIONS["target"], _OPTIONS["subtarget"])
links {
"osd_" .. _OPTIONS["osd"],
}
links {
"qtdbg_" .. _OPTIONS["osd"],
}
links {
"netlist",
"optional",
"emu",
"formats",
}
if #disasm_files > 0 then
links {
"dasm",
}
end
links {
"utils",
"expat",
"softfloat",
"jpeg",
"7z",
"lua",
"lualibs",
}
if _OPTIONS["USE_LIBUV"]=="1" then
links {
"uv",
"http-parser",
}
end
if _OPTIONS["with-bundled-zlib"] then
links {
"zlib",
}
else
links {
"z",
}
end
if _OPTIONS["with-bundled-flac"] then
links {
"flac",
}
else
links {
"FLAC",
}
end
if _OPTIONS["with-bundled-sqlite3"] then
links {
"sqllite3",
}
else
links {
"sqlite3",
}
end
if _OPTIONS["NO_USE_MIDI"]~="1" then
links {
"portmidi",
}
end
links {
"bgfx",
"ocore_" .. _OPTIONS["osd"],
}
override_resources = false;
maintargetosdoptions(_target,_subtarget)
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/emu",
MAME_DIR .. "src/devices",
MAME_DIR .. "src/" .. _target,
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
GEN_DIR .. _target .. "/layout",
GEN_DIR .. "resource",
}
if _OPTIONS["with-bundled-zlib"] then
includedirs {
MAME_DIR .. "3rdparty/zlib",
}
end
if _OPTIONS["targetos"]=="macosx" and (not override_resources) then
linkoptions {
"-sectcreate __TEXT __info_plist " .. _MAKE.esc(GEN_DIR) .. "resource/" .. _subtarget .. "-Info.plist"
}
custombuildtask {
{ MAME_DIR .. "src/version.cpp" , GEN_DIR .. "resource/" .. _subtarget .. "-Info.plist", { MAME_DIR .. "scripts/build/verinfo.py" }, {"@echo Emitting " .. _subtarget .. "-Info.plist" .. "...", PYTHON .. " $(1) -p -b " .. _subtarget .. " $(<) > $(@)" }},
}
dependency {
{ "$(TARGET)" , GEN_DIR .. "resource/" .. _subtarget .. "-Info.plist", true },
}
end
local rctarget = _subtarget
if _OPTIONS["targetos"]=="windows" and (not override_resources) then
local rcfile = MAME_DIR .. "src/" .. _target .. "/osd/".._OPTIONS["osd"].."/" .. _subtarget .. "/" .. rctarget ..".rc"
if not os.isfile(rcfile) then
rcfile = MAME_DIR .. "src/" .. _target .. "/osd/windows/" .. _subtarget .. "/" .. rctarget ..".rc"
end
if os.isfile(rcfile) then
files {
rcfile,
}
dependency {
{ "$(OBJDIR)/".._subtarget ..".res" , GEN_DIR .. "resource/" .. rctarget .. "vers.rc", true },
}
else
rctarget = "mame"
files {
MAME_DIR .. "src/mame/osd/windows/mame/mame.rc",
}
dependency {
{ "$(OBJDIR)/mame.res" , GEN_DIR .. "resource/" .. rctarget .. "vers.rc", true },
}
end
end
local mainfile = MAME_DIR .. "src/".._target .."/" .. _subtarget ..".cpp"
if not os.isfile(mainfile) then
mainfile = MAME_DIR .. "src/".._target .."/" .. _target ..".cpp"
end
files {
mainfile,
MAME_DIR .. "src/version.cpp",
GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp",
}
if (_OPTIONS["SOURCES"] == nil) then
if os.isfile(MAME_DIR .. "src/".._target .."/" .. _subtarget ..".flt") then
dependency {
{
GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp", MAME_DIR .. "src/".._target .."/" .. _target ..".lst", true },
}
custombuildtask {
{ MAME_DIR .. "src/".._target .."/" .. _subtarget ..".flt" , GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp", { MAME_DIR .. "scripts/build/makelist.py", MAME_DIR .. "src/".._target .."/" .. _target ..".lst" }, {"@echo Building driver list...", PYTHON .. " $(1) $(2) $(<) > $(@)" }},
}
else
if os.isfile(MAME_DIR .. "src/".._target .."/" .. _subtarget ..".lst") then
custombuildtask {
{ MAME_DIR .. "src/".._target .."/" .. _subtarget ..".lst" , GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp", { MAME_DIR .. "scripts/build/makelist.py" }, {"@echo Building driver list...", PYTHON .. " $(1) $(<) > $(@)" }},
}
else
dependency {
{
GEN_DIR .. _target .. "/" .. _target .."/drivlist.cpp", MAME_DIR .. "src/".._target .."/" .. _target ..".lst", true },
}
custombuildtask {
{ MAME_DIR .. "src/".._target .."/" .. _target ..".lst" , GEN_DIR .. _target .. "/" .. _target .."/drivlist.cpp", { MAME_DIR .. "scripts/build/makelist.py" }, {"@echo Building driver list...", PYTHON .. " $(1) $(<) > $(@)" }},
}
end
end
end
if (_OPTIONS["SOURCES"] ~= nil) then
dependency {
{
GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp", MAME_DIR .. "src/".._target .."/" .. _target ..".lst", true },
}
custombuildtask {
{ GEN_DIR .. _target .."/" .. _subtarget ..".flt" , GEN_DIR .. _target .. "/" .. _subtarget .."/drivlist.cpp", { MAME_DIR .. "scripts/build/makelist.py", MAME_DIR .. "src/".._target .."/" .. _target ..".lst" }, {"@echo Building driver list...", PYTHON .. " $(1) $(2) $(<) > $(@)" }},
}
end
if _OPTIONS["FORCE_VERSION_COMPILE"]=="1" then
configuration { "gmake" }
dependency {
{ ".PHONY", ".FORCE", true },
{ "$(OBJDIR)/src/version.o", ".FORCE", true },
}
end
configuration { "mingw*" }
custombuildtask {
{ MAME_DIR .. "src/version.cpp" , GEN_DIR .. "resource/" .. rctarget .. "vers.rc", { MAME_DIR .. "scripts/build/verinfo.py" }, {"@echo Emitting " .. rctarget .. "vers.rc" .. "...", PYTHON .. " $(1) -r -b " .. rctarget .. " $(<) > $(@)" }},
}
configuration { "vs*" }
prebuildcommands {
"mkdir " .. path.translate(GEN_DIR .. "resource/","\\") .. " 2>NUL",
"@echo Emitting ".. rctarget .. "vers.rc...",
PYTHON .. " " .. path.translate(MAME_DIR .. "scripts/build/verinfo.py","\\") .. " -r -b " .. rctarget .. " " .. path.translate(MAME_DIR .. "src/version.cpp","\\") .. " > " .. path.translate(GEN_DIR .. "resource/" .. rctarget .. "vers.rc", "\\") ,
}
configuration { }
debugdir (MAME_DIR)
debugargs ("-window")
end
| gpl-2.0 |
abriasffxi/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/npcs/Credaurion_RK.lua | 14 | 3393 | -----------------------------------
-- Area: The Sanctuary of Zi'Tah
-- NPC: Credaurion, R.K.
-- Outpost Conquest Guards
-- @pos -40.079 -0.642 -148.785 121
-----------------------------------
package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/conquest");
require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = LITELOR;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
cjtallman/LDoc | ldoc/builtin/os.lua | 7 | 4824 | --- Operating System facilities like date, time and program execution.
-- @module os
local os = {}
---
-- Returns an approximation of the amount in seconds of CPU time used by
-- the program.
function os.clock() end
---
-- Returns a string or a table containing date and time, formatted according
-- to the given string `format`.
--
-- If the `time` argument is present, this is the time to be formatted
-- (see the `os.time` function for a description of this value). Otherwise,
-- `date` formats the current time.
--
-- If `format` starts with '`!`', then the date is formatted in Coordinated
-- Universal Time. After this optional character, if `format` is the string
-- "`*t`", then `date` returns a table with the following fields:
--
-- * `year` (four digits)
-- * `month` (1--12)
-- * `day` (1--31)
-- * `hour` (0--23)
-- * `min` (0--59)
-- * `sec` (0--61)
-- * `wday` (weekday, Sunday is 1)
-- * `yday` (day of the year)
-- * `isdst` (daylight saving flag, a boolean).
--
-- If `format` is not "`*t`", then `date` returns the date as a string,
-- formatted according to the same rules as the C function `strftime`.
-- When called without arguments, `date` returns a reasonable date and time
-- representation that depends on the host system and on the current locale
-- (that is, `os.date()` is equivalent to `os.date("%c")`).
function os.date(format , time) end
---
-- Returns the number of seconds from time `t1` to time `t2`. In POSIX,
-- Windows, and some other systems, this value is exactly `t2`*-*`t1`.
function os.difftime(t2, t1) end
---
-- This function is equivalent to the C function `system`. It passes
-- `command` to be executed by an operating system shell. It returns a status
-- code, which is system-dependent. If `command` is absent, then it returns
-- nonzero if a shell is available and zero otherwise.
function os.execute(command) end
---
-- Calls the C function `exit`, with an optional `code`, to terminate the
-- host program. The default value for `code` is the success code.
function os.exit(code) end
---
-- Returns the value of the process environment variable `varname`, or
-- nil if the variable is not defined.
function os.getenv(varname) end
---
-- Deletes the file or directory with the given name. Directories must be
-- empty to be removed. If this function fails, it returns nil, plus a string
-- describing the error.
function os.remove(filename) end
---
-- Renames file or directory named `oldname` to `newname`. If this function
-- fails, it returns nil, plus a string describing the error.
function os.rename(oldname, newname) end
---
-- Sets the current locale of the program. `locale` is a string specifying
-- a locale; `category` is an optional string describing which category to
-- change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`, `"numeric"`, or
-- `"time"`; the default category is `"all"`. The function returns the name
-- of the new locale, or nil if the request cannot be honored.
-- If `locale` is the empty string, the current locale is set to an
-- implementation-defined native locale. If `locale` is the string "`C`",
-- the current locale is set to the standard C locale.
-- When called with nil as the first argument, this function only returns
-- the name of the current locale for the given category.
function os.setlocale(locale , category) end
---
-- Returns the current time when called without arguments, or a time
-- representing the date and time specified by the given table. This table
-- must have fields `year`, `month`, and `day`, and may have fields `hour`,
-- `min`, `sec`, and `isdst` (for a description of these fields, see the
-- `os.date` function).
-- The returned value is a number, whose meaning depends on your system. In
-- POSIX, Windows, and some other systems, this number counts the number
-- of seconds since some given start time (the "epoch"). In other systems,
-- the meaning is not specified, and the number returned by `time` can be
-- used only as an argument to `date` and `difftime`.
function os.time(table) end
---
-- Returns a string with a file name that can be used for a temporary
-- file. The file must be explicitly opened before its use and explicitly
-- removed when no longer needed.
-- On some systems (POSIX), this function also creates a file with that
-- name, to avoid security risks. (Someone else might create the file with
-- wrong permissions in the time between getting the name and creating the
-- file.) You still have to open the file to use it and to remove it (even
-- if you do not use it).
-- When possible, you may prefer to use `io.tmpfile`, which automatically
-- removes the file when the program ends.
function os.tmpname() end
return os
| mit |
jebenexer/kong | kong/templates/kong_defaults.lua | 1 | 2201 | return [[
prefix = /usr/local/kong/
log_level = notice
proxy_access_log = logs/access.log
proxy_error_log = logs/error.log
admin_access_log = logs/admin_access.log
admin_error_log = logs/error.log
custom_plugins = NONE
anonymous_reports = on
proxy_listen = 0.0.0.0:8000
proxy_listen_ssl = 0.0.0.0:8443
admin_listen = 127.0.0.1:8001
admin_listen_ssl = 127.0.0.1:8444
nginx_user = nobody nobody
nginx_worker_processes = auto
nginx_optimizations = on
nginx_daemon = on
mem_cache_size = 128m
http2 = off
ssl = on
ssl_cert = NONE
ssl_cert_key = NONE
client_ssl = off
client_ssl_cert = NONE
client_ssl_cert_key = NONE
ssl_cipher_suite = modern
ssl_ciphers = ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256
admin_http2 = off
admin_ssl = on
admin_ssl_cert = NONE
admin_ssl_cert_key = NONE
upstream_keepalive = 60
server_tokens = on
latency_tokens = on
trusted_ips = NONE
real_ip_header = X-Real-IP
real_ip_recursive = off
client_max_body_size = 0
client_body_buffer_size = 8k
error_default_type = text/plain
database = postgres
pg_host = 127.0.0.1
pg_port = 5432
pg_database = kong
pg_user = kong
pg_password = NONE
pg_ssl = off
pg_ssl_verify = off
cassandra_contact_points = 127.0.0.1
cassandra_port = 9042
cassandra_keyspace = kong
cassandra_timeout = 5000
cassandra_ssl = off
cassandra_ssl_verify = off
cassandra_username = kong
cassandra_password = NONE
cassandra_consistency = ONE
cassandra_lb_policy = RoundRobin
cassandra_local_datacenter = NONE
cassandra_repl_strategy = SimpleStrategy
cassandra_repl_factor = 1
cassandra_data_centers = dc1:2,dc2:3
cassandra_schema_consensus_timeout = 10000
db_update_frequency = 5
db_update_propagation = 0
db_cache_ttl = 3600
dns_resolver = NONE
dns_hostsfile = /etc/hosts
dns_order = LAST,SRV,A,CNAME
dns_stale_ttl = 4
dns_not_found_ttl = 30
dns_error_ttl = 1
dns_no_sync = off
lua_socket_pool_size = 30
lua_ssl_trusted_certificate = NONE
lua_ssl_verify_depth = 1
lua_package_path = ./?.lua;./?/init.lua;
lua_package_cpath = NONE
]]
| apache-2.0 |
abriasffxi/darkstar | scripts/zones/Bastok_Mines/npcs/Christina.lua | 14 | 1047 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Christina
-- Type: Special Event Coordinator
-- @zone 234
-- @pos 23.703 -1 -86.034
--
-- Auto-Script: Requires Verification
-----------------------------------
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)
player:startEvent(0x7fb2);
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 |
abriasffxi/darkstar | scripts/zones/Gusgen_Mines/npcs/_5g7.lua | 14 | 2970 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Strange Apparatus
-- @pos 219 -39 255 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
require("scripts/zones/Gusgen_Mines/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0002, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0000, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0000) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
uspgamedev/backdoor | game/gamestates/user_turn.lua | 1 | 9159 | --- MODULE FOR THE GAMESTATE: PLAYER TURN
-- This gamestate rolls out when the player's turn arrives. It pops the action
-- the player chose to do.
-- luacheck: globals SWITCHER GS, no self
local DEFS = require 'domain.definitions'
local DIR = require 'domain.definitions.dir'
local ACTION = require 'domain.action'
local ABILITY = require 'domain.ability'
local PROFILE = require 'infra.profile'
local PLAYSFX = require 'helpers.playsfx'
local ActionHUD = require 'view.gameplay.actionhud'
local SCHEMATICS = require 'domain.definitions.schematics'
local INPUT = require 'input'
local Draw = require "draw"
local state = {}
--[[ Local Variables ]]--
local _task
local _route
local _next_action
local _view
local _save_and_quit
local _ACTION = {}
--[[ Local functions ]]--
local _checkTutorial
local _update_panel
--[[ Task Functions ]]--
local function _resumeTask(...)
if _task then
local ok, result = coroutine.resume(_task, ...)
if ok then
_task = result
else
error(debug.traceback(_task, result))
end
end
end
local function _startTask(action, ...)
local controlled_actor = _route.getControlledActor()
local callback = _ACTION[action]
if controlled_actor and not _next_action then
_task = coroutine.create(callback)
return _resumeTask(...)
end
end
--[[ State Methods ]]--
function state:enter(_, route, view)
_route = route
_save_and_quit = false
_view = view
_view.action_hud:enableTurn(true)
_view.action_hud:refreshTurnPreview()
_view.sector:snapBodyViews()
_update_panel("isdown")
end
function state:leave()
_view.action_hud:disableTurnPreview()
end
function state:resume(_, args)
_update_panel("isdown")
_view.action_hud:enableTurn(true)
_resumeTask(args)
end
function state:devmode()
_view.action_hud:disableTurn()
end
function state:update(_)
if _checkTutorial() then return end
if _save_and_quit then return SWITCHER.pop("SAVE_AND_QUIT") end
_view.sector:lookAt(_route.getControlledActor())
if _next_action then
SWITCHER.pop({next_action = _next_action})
_next_action = nil
return
end
_update_panel("waspressed")
local action_request, param = _view.action_hud:actionRequested()
if action_request == ActionHUD.INTERFACE_COMMANDS.SAVE_QUIT then
_save_and_quit = true
elseif action_request then
_startTask(action_request, param)
end
end
function state:draw()
Draw.allTables()
end
--[[ Action functions ]]--
local function _useAction(action_slot, params)
if not ACTION.exists(action_slot) then return false end
local controlled_actor = _route.getControlledActor()
params = params or {}
local param = ACTION.pendingInput(action_slot, controlled_actor, params)
while param do
_view.action_hud:activateAbility()
if param.name == 'choose_dir' then
_view.action_hud:disableTurn()
if params.card_index then
local card = controlled_actor:getHandCard(params.card_index)
_view.action_hud.infopanel:lockElement(card)
end
SWITCHER.push(GS.PICK_DIR, _view.sector, param)
local dir = coroutine.yield(_task)
_view.action_hud.infopanel:lockElement()
if dir then
params[param.output] = dir
else
return false
end
elseif param.name == 'choose_target' then
_view.action_hud:disableTurn()
if params.card_index then
local card = controlled_actor:getHandCard(params.card_index)
_view.action_hud.infopanel:lockElement(card)
end
SWITCHER.push(
GS.PICK_TARGET, _view.sector,
{
card = ACTION.card(action_slot, controlled_actor, params),
pos = { controlled_actor:getPos() },
aoe_hint = param['aoe-hint'],
range_checker = function(i, j)
return ABILITY.input('choose_target')
.isWithinRange(controlled_actor, param, {i,j})
end,
validator = function(i, j)
return ABILITY.validate('choose_target', controlled_actor, param,
{i,j})
end
}
)
local args = coroutine.yield(_task)
_view.action_hud.infopanel:lockElement()
if args.target_is_valid then
params[param.output] = args.pos
else
return false
end
elseif param.name == "choose_consume_list" then
_view.action_hud:disableTurn()
SWITCHER.push(GS.CONSUME_CARDS, _view, controlled_actor, param.max)
local args = coroutine.yield(_task)
if args.consumed then
params[param.output] = args.consumed
else
return false
end
end
param = ACTION.pendingInput(action_slot, controlled_actor, params)
end
_next_action = {action_slot, params}
return true
end
_ACTION[DEFS.ACTION.MOVE] = function (dir)
local current_sector = _route.getCurrentSector()
local controlled_actor = _route.getControlledActor()
local i, j = controlled_actor:getPos()
dir = DIR[dir]
i, j = i+dir[1], j+dir[2]
if current_sector:isValid(i,j) then
_useAction(DEFS.ACTION.MOVE, { pos = {i,j} })
else
PLAYSFX('denied')
end
end
_ACTION[DEFS.ACTION.INTERACT] = function()
_useAction(DEFS.ACTION.INTERACT)
end
_ACTION[DEFS.ACTION.PLAY_CARD] = function(card_index)
local actor = _route.getControlledActor()
local card = actor:getHandCard(card_index)
if actor:canPlayCard(card) then
PLAYSFX('ok-menu')
_useAction(DEFS.ACTION.PLAY_CARD, { card_index = card_index })
else
PLAYSFX('denied')
end
end
_ACTION[DEFS.ACTION.DISCARD_CARD] = function(card_index)
PLAYSFX('ok-menu')
_useAction(DEFS.ACTION.DISCARD_CARD, { card_index = card_index })
end
_ACTION[DEFS.ACTION.CONSUME_CARDS] = function()
local actor = _route.getControlledActor()
if actor:getBackBufferSize() > 0 then
PLAYSFX('ok-menu')
_view.action_hud:disableTurn()
SWITCHER.push(GS.MANAGE_BUFFER, actor)
coroutine.yield(_task)
else
PLAYSFX('denied')
end
end
_ACTION[DEFS.ACTION.RECEIVE_PACK] = function()
local actor = _route.getControlledActor()
if actor:getPrizePackCount() > 0 then
PLAYSFX('ok-menu')
_view.action_hud:disableTurn()
SWITCHER.push(GS.OPEN_PACK, _view, _route, actor:getPrizePacks())
local args = coroutine.yield(_task)
if args.pack == nil then return end
if args.pack_index == "all" then
_route.getControlledActor():removeAllPacks()
else
_route.getControlledActor():removePrizePack(args.pack_index)
end
_useAction(DEFS.ACTION.RECEIVE_PACK,
{ consumed = args.consumed, pack = args.pack })
else
PLAYSFX('denied')
end
end
_ACTION[DEFS.ACTION.IDLE] = function()
_useAction(DEFS.ACTION.IDLE)
end
function _update_panel(mode)
if mode == "isdown" then
if INPUT.isActionDown('STATUS') then
_view.actor:show()
else
_view.actor:hide()
end
elseif mode == "waspressed" then
if INPUT.wasActionPressed('STATUS') then
_view.actor:show()
elseif INPUT.wasActionReleased('STATUS') then
_view.actor:hide()
end
else
error("Not a valid mode to update panel")
end
end
function _checkTutorial()
--Check for first time seeing a damageable target
if not PROFILE.getTutorial("open_hand") then
local player = _route.getPlayerActor()
if player then
local player_i, player_j = player:getPos()
local hostile_bodies = player:getBodiesInFactions({'aggressive', 'inert'})
for _,body in ipairs(hostile_bodies) do
local enemy_i, enemy_j = body:getPos()
if math.abs(player_i - enemy_i) + math.abs(player_j - enemy_j) <= 1 then
SWITCHER.push(GS.TUTORIAL_HINT, "open_hand")
return true
end
end
end
end
-- Check for first time seeing an altar
if not PROFILE.getTutorial("altar") then
local player = _route.getPlayerActor()
if player then
local altars = player:getVisibleTilesIf(function (sector, i, j)
local tile = sector:getTile(i, j)
return tile and tile.type == SCHEMATICS.ALTAR
end)
if #altars > 0 then
local altar_tile = altars[1]
local player_i, player_j = player:getPos()
local relative_pos = { altar_tile.i - player_i,
altar_tile.j - player_j }
SWITCHER.push(GS.TUTORIAL_HINT, "altar", relative_pos)
return true
end
end
end
-- Check for first time seeing stairs
if not PROFILE.getTutorial("use_stairs") then
local player = _route.getPlayerActor()
if player then
local stairs_tiles = player:getVisibleTilesIf(function (sector, i, j)
local tile = sector:getTile(i, j)
return tile and tile.type == SCHEMATICS.EXITDOWN
end)
if #stairs_tiles > 0 then
local stairs_tile = stairs_tiles[1]
local player_i, player_j = player:getPos()
local relative_pos = { stairs_tile.i - player_i,
stairs_tile.j - player_j }
SWITCHER.push(GS.TUTORIAL_HINT, "use_stairs", relative_pos)
return true
end
end
end
end
return state
| gpl-3.0 |
Armyluix/darkstar | scripts/zones/Morimar_Basalt_Fields/Zone.lua | 34 | 1267 | -----------------------------------
--
-- Zone: Morimar Basalt Fields
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Morimar_Basalt_Fields/TextIDs"] = nil;
require("scripts/zones/Morimar_Basalt_Fields/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(579,-7,-484,199);
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 |
ElectroDuk/QuackWars | garrysmod/addons/ulib/lua/ulib/server/phys.lua | 3 | 4105 | --[[
Title: Physics Helpers
Various functions to make dealing with the HL2 physics engine a little easier.
]]
--[[
Function: applyAccel
Parameters:
ent - The entity to apply the acceleration to
magnitude - The amount of acceleration ( Use nil if the magnitude is specified in the direction )
direction - The direction to apply the acceleration in ( if the magnitude is part of the direction, specify nil for the magnitude )
dTime - *(Optional, defaults to 1)* The time passed since the last update in seconds ( IE: 0.5 for dTime would only apply half the acceleration )
]]
function ULib.applyAccel( ent, magnitude, direction, dTime )
if dTime == nil then dTime = 1 end
if magnitude ~= nil then
direction:Normalize()
else
magnitude = 1
end
-- Times it by the time elapsed since the last update.
local accel = magnitude * dTime
-- Convert our scalar accel to a vector accel
accel = direction * accel
if ent:GetMoveType() == MOVETYPE_VPHYSICS then
-- a = f/m , so times by mass to get the force.
local force = accel * ent:GetPhysicsObject():GetMass()
ent:GetPhysicsObject():ApplyForceCenter( force )
else
ent:SetVelocity( accel ) -- As it turns out, SetVelocity() is actually SetAccel() in GM10
end
end
--[[
Function: applyForce
Parameters:
ent - The entity to apply the force to
magnitude - The amount of force ( Use nil if the magnitude is specified in the direction )
direction - The direction to apply the force in ( if the magnitude is part of the direction, specify nil for the magnitude )
dTime - *(Optional, defaults to 1)* The time passed since the last update in seconds ( IE: 0.5 for dTime would only apply half the force )
]]
function ULib.applyForce( ent, magnitude, direction, dTime )
if dTime == nil then dTime = 1 end
if magnitude ~= nil then
direction:Normalize()
else
magnitude = 1
end
-- Times it by the time elapsed since the last update.
local force = magnitude * dTime
-- Convert our scalar force to a vector force
force = direction * force
if ent:GetMoveType() == MOVETYPE_VPHYSICS then
ent:GetPhysicsObject():ApplyForceCenter( force )
else
-- Because we're not dealing with objects that have vphysics, they might not have a mass. This would cause errors, let's catch them here.
local mass = ent:GetPhysicsObject():GetMass()
if not mass then
mass = 1
Msg( "applyForce was called with a non-physics entity that doesn't have a mass. To continue calculations, we're assuming it has a mass of one. This could very well produce unrealistic looking physics!\n")
end
-- f = m*a, so divide it by mass to get the accel
local accel = force * 1/mass
ent:SetVelocity( accel ) -- As it turns out, SetVelocity() is actually SetAccel() in GM10
end
end
--[[
Function: applyAccelInCurDirection
Applies an acceleration in the entities current *velocity* direction ( not the entity's heading ). See <applyAccel>.
Basically makes the entity go faster or slower ( if a negative magnitude is passed ).
Parameters:
ent - The entity to apply the force to
magnitude - The amount of acceleration
dTime - *(Optional, defaults to 1)* The time passed since the last update in seconds ( IE: 0.5 for dTime would only apply half the acceleration )
]]
function ULib.applyAccelInCurDirection( ent, magnitude, dTime )
local direction = ent:GetVelocity( entid ):GetNormalized()
ULib.applyAccel( entid, magnitude, direction, dTime )
end
--[[
Function: applyForceInCurDirection
Applies a force in the entities current *velocity* direction ( not the entity's heading ). See <applyForce>.
Basically makes the entity go faster or slower ( if a negative magnitude is passed ).
Parameters:
ent - The entity to apply the force to
magnitude - The amount of force
dTime - *(Optional, defaults to 1)* The time passed since the last update in seconds ( IE: 0.5 for dTime would only apply half the force )
]]
function ULib.applyForceInCurDirection( ent, magnitude, dTime )
local direction = ent:GetVelocity( entid ):GetNormalized()
ULib.applyForce( entid, magnitude, direction, dTime )
end | mit |
Armyluix/darkstar | scripts/globals/weaponskills/decimation.lua | 30 | 1511 | -----------------------------------
-- Decimation
-- Axe weapon skill
-- Skill level: 240
-- In order to obtain Decimation, the quest Axe the Competition must be completed.
-- Delivers a three-hit attack. params.accuracy varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget.
-- Aligned with the Flame Belt, Light Belt & Aqua Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.25 1.25 1.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1.25; params.ftp200 = 1.25; params.ftp300 = 1.25;
params.str_wsc = 0.5; 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.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.75; params.ftp200 = 1.75; params.ftp300 = 1.75;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Armyluix/darkstar | scripts/globals/spells/bluemagic/disseverment.lua | 28 | 2124 | -----------------------------------------
-- Spell: Disseverment
-- Delivers a fivefold attack. Additional effect: Poison. Accuracy varies with TP
-- Spell cost: 74 MP
-- Monster Type: Luminians
-- Spell Type: Physical (Piercing)
-- Blue Magic Points: 5
-- Stat Bonus: INT+1, MND-1
-- Level: 72
-- Casting Time: 0.5 seconds
-- Recast Time: 32.75 seconds
-- Skillchain Element(s): Distortion (can open/close Darkness with Gravitation WSs and spells)
-- Combos: Accuracy Bonus
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_ACC;
params.dmgtype = DMGTYPE_PIERCE;
params.scattr = SC_DISTORTION;
params.numhits = 5;
params.multiplier = 1.5;
params.tp150 = 0.8;
params.tp300 = 1.0;
params.azuretp = 1.0;
params.duppercap = 100; -- D upper >=69
params.str_wsc = 0.2;
params.dex_wsc = 0.2;
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;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
poison = target:getStatusEffect(EFFECT_POISON);
local chance = math.random();
if (chance < 0.95 and poison == nil) then
local power = (caster:getMainLvl()/5) + 3; -- from http://wiki.ffxiclopedia.org/wiki/Disseverment
target:addStatusEffect(EFFECT_POISON,power,3,180); -- for 180secs
end
return damage;
end; | gpl-3.0 |
Armyluix/darkstar | scripts/zones/Davoi/Zone.lua | 17 | 3157 | -----------------------------------
--
-- Zone: Davoi (149)
--
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(17388023);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(282.292,2.498,-17.908,247);
end
if (player:getCurrentMission(SANDORIA) == INFILTRATE_DAVOI and player:getVar("MissionStatus") == 2) then
cs = 0x0074;
end
if (player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_ACCEPTED and GetMobAction(17387969) == 0) then
SpawnMob(17387969); -- Spawned by Quest: The Crimson Trial upon entering the zone.
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onGameDay
-----------------------------------
function onGameDay()
-- Storage Hole
local storHolePos = {--[[E-10]]{-177.925,4.000,-255.699},--[[F-6]]{-127.703,4.250,23.732}, --[[F-7]]{-127.822,4.250,-16.964},--[[F-9]]{-123.369,4.000,-231.972},--[[G-9]]{-51.570,4.127,-216.462},
--[[G-10]]{-55.960,2.958,-300.014}, --[[I-7]]{152.311,4.000,-74.176}, --[[I-8]]{153.514,4.250,-112.616},--[[J-7]]{188.988,4.000,-80.058}, --[[K-7]]{318.694,0.001,-58.646},
--[[K-8]]{299.717,0.001,-160.910}, --[[K-9]]{274.849,4.162,-213.599},--[[K-9]]{250.809,4.000,-240.509},--[[J-8]]{219.474,3.750,-128.170}, --[[I-9]]{86.749,-5.166,-166.414}};
local storageHole = GetNPCByID(17388021);
local randPos = 0;
while(randPos == 0 or storHolePos[randPos][1] == storageHole:getXPos()) do
randPos = math.random(1,15);
end
storageHole:setPos(storHolePos[randPos][1],storHolePos[randPos][2],storHolePos[randPos][3],0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0074) then
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
Armyluix/darkstar | scripts/zones/Port_San_dOria/npcs/_6g7.lua | 17 | 1145 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Door: Arrivals Entrance
-- @zone 232
-- @pos -24 -8 15
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() >= 12) then
player:startEvent(0x0206);
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 |
Armyluix/darkstar | scripts/zones/Upper_Jeuno/npcs/_6s1.lua | 17 | 4057 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Marble Bridge Eatery (Door)
-- @pos -96.6 -0.2 92.3 244
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Upper_Jeuno/TextIDs");
local RajasRing = 15543;
local SattvaRing = 15544;
local TamasRing = 15545;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local playerhaveCOPring=false;
local ringtakeNbr=player:getVar("COP-RingTakeNbr");
local currentday = tonumber(os.date("%j"));
local lastRingday =player:getVar("COP-lastRingday");
if (player:hasItem(RajasRing) or player:hasItem(SattvaRing) or player:hasItem(TamasRing)) then
playerhaveCOPring=true;
end
if (player:getCurrentMission(COP) == FOR_WHOM_THE_VERSE_IS_SUNG and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x271B);
elseif (player:getCurrentMission(COP) ==FLAMES_IN_THE_DARKNESS and player:getVar("PromathiaStatus")==3) then
player:startEvent(0x271C);
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")== 4) then
player:startEvent(0x0081);
elseif ((player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")> 4) or player:hasCompletedMission(COP,DAWN)) then
if (playerhaveCOPring == false ) then
if (ringtakeNbr==0) then
player:startEvent(0x0054,RajasRing,SattvaRing,TamasRing);
elseif (ringtakeNbr ==1) then -- First time you throw away
player:startEvent(0x00CC,RajasRing,SattvaRing,TamasRing);
elseif (ringtakeNbr >1 and (currentday-lastRingday)>26) then -- Ring was thrown away more than once
player:startEvent(0x00CC,RajasRing,SattvaRing,TamasRing);
end
end
else
return -1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
local currentday = tonumber(os.date("%j"));
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
local ringtakeNbr=player:getVar("COP-RingTakeNbr");
if (csid == 0x271B) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x271C) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,FLAMES_IN_THE_DARKNESS);
player:addMission(COP,FIRE_IN_THE_EYES_OF_MEN);
elseif (csid == 0x0081) then
player:setVar("PromathiaStatus",5);
elseif ((csid == 0x0054 or csid == 0x00CC) and option > 4 and player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,(option-5)+RajasRing);
elseif ((csid == 0x0054 or csid == 0x00CC)and option == 5) then--5 rajas
player:addItem(RajasRing);
player:messageSpecial(ITEM_OBTAINED,RajasRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
elseif ((csid == 0x0054 or csid == 0x00CC)and option == 6) then--6 Sattva
player:addItem(SattvaRing);
player:messageSpecial(ITEM_OBTAINED,SattvaRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
elseif ((csid == 0x0054 or csid == 0x00CC) and option == 7) then--7 Tamas
player:addItem(TamasRing);
player:messageSpecial(ITEM_OBTAINED,TamasRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
end
end;
| gpl-3.0 |
urueedi/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/olsrd.lua | 43 | 1470 | -- Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("OLSRd Plugin Configuration"),
translate("The OLSRd plugin reads information about meshed networks from the txtinfo plugin of OLSRd."))
s = m:section(NamedSection, "collectd_olsrd", "luci_statistics" )
enable = s:option(Flag, "enable", translate("Enable this plugin"))
enable.default = 0
host = s:option(Value, "Host", translate("Host"), translate("IP or hostname where to get the txtinfo output from"))
host.placeholder = "127.0.0.1"
host.datatype = "host"
host.rmempty = true
port = s:option(Value, "Port", translate("Port"))
port.placeholder = "2006"
port.datatype = "range(0,65535)"
port.rmempty = true
port.cast = "string"
cl = s:option(ListValue, "CollectLinks", translate("CollectLinks"),
translate("Specifies what information to collect about links."))
cl:value("No")
cl:value("Summary")
cl:value("Detail")
cl.default = "Detail"
cr = s:option(ListValue, "CollectRoutes", translate("CollectRoutes"),
translate("Specifies what information to collect about routes."))
cr:value("No")
cr:value("Summary")
cr:value("Detail")
cr.default = "Summary"
ct = s:option(ListValue, "CollectTopology", translate("CollectTopology"),
translate("Specifies what information to collect about the global topology."))
ct:value("No")
ct:value("Summary")
ct:value("Detail")
ct.default = "Summary"
return m
| apache-2.0 |
abriasffxi/darkstar | scripts/zones/Meriphataud_Mountains/npcs/Mushosho.lua | 14 | 1935 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Mushosho
-- Type: Outpost Vendor
-- @pos -290 16 415 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Meriphataud_Mountains/TextIDs");
local region = ARAGONEU;
local csid = 0x7ff4;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local owner = GetRegionOwner(region);
local arg1 = getArg1(owner,player);
if (owner == player:getNation()) then
nation = 1;
elseif (arg1 < 1792) then
nation = 2;
else
nation = 0;
end
player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP());
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
ShowOPVendorShop(player);
elseif (option == 2) then
if (player:delGil(OP_TeleFee(player,region))) then
toHomeNation(player);
end
elseif (option == 6) then
player:delCP(OP_TeleFee(player,region));
toHomeNation(player);
end
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Gusgen_Mines/npcs/_5g3.lua | 14 | 1103 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5g3 (Door F)
-- @pos 44 -22.399 174.494 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(LOCK_OTHER_DEVICE)
else
return 0;
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 |
Armyluix/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/qm2.lua | 17 | 1773 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: qm2 (???)
-- Involved In Quest: 20 in Pirate Years
-- @pos 47.852 -7.808 403.391 114
-----------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
twentyInPirateYearsCS = player:getVar("twentyInPirateYearsCS");
TsuchigumoKilled = player:getVar("TsuchigumoKilled");
if (twentyInPirateYearsCS == 3 and TsuchigumoKilled <= 1) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17244524,300):updateClaim(player);
SpawnMob(17244525,300):updateClaim(player);
elseif (twentyInPirateYearsCS == 3 and TsuchigumoKilled >= 2) then
player:addKeyItem(TRICK_BOX);
player:messageSpecial(KEYITEM_OBTAINED,TRICK_BOX);
player:setVar("twentyInPirateYearsCS",4);
player:setVar("TsuchigumoKilled",0);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
abriasffxi/darkstar | scripts/zones/Northern_San_dOria/npcs/Mulaujeant.lua | 27 | 2466 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Mulaujeant
-- Involved in Quests: Missionary Man
-- @zone 231
-- @pos -175 0 181
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
starttime = player:getVar("MissionaryMan_date");
MissionaryManVar = player:getVar("MissionaryManVar");
if (MissionaryManVar == 2) then
player:startEvent(0x02ba,0,1146); -- Start statue creation
elseif (MissionaryManVar == 3 and (starttime == realday or player:needToZone() == true)) then
player:startEvent(0x02bb); -- During statue creation
elseif (MissionaryManVar == 3 and starttime ~= realday and player:needToZone() == false) then
player:startEvent(0x02bc); -- End of statue creation
elseif (MissionaryManVar == 4) then
player:startEvent(0x02bd); -- During quest (after creation)
else
player:startEvent(0x02b9); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x02ba) then
player:setVar("MissionaryManVar",3);
player:setVar("MissionaryMan_date", os.date("%j")); -- %M for next minute, %j for next day
player:delKeyItem(RAUTEINOTS_PARCEL);
player:needToZone(true);
elseif (csid == 0x02bc) then
player:setVar("MissionaryManVar",4);
player:setVar("MissionaryMan_date", 0);
player:addKeyItem(SUBLIME_STATUE_OF_THE_GODDESS);
player:messageSpecial(KEYITEM_OBTAINED,SUBLIME_STATUE_OF_THE_GODDESS);
end
end;
| gpl-3.0 |
Armyluix/darkstar | scripts/zones/Qufim_Island/npcs/Hieroglyphics.lua | 17 | 2172 | -----------------------------------
-- Area: Qufim_Island
-- NPC: Hieroglyphics
-- Dynamis Qufim Entrance
-- @pos 117 -10 133 172 118
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Qufim_Island/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaQufim]UniqueID")) then
player:startEvent(0x0003,9,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
--printf("dayRemaining : %u",dayRemaining );
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,8);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
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);
if (csid == 0x0003 and option == 0) then
player:setPos(-19,-17,104,253,41);
end
end; | gpl-3.0 |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/cocos/scripting/lua-bindings/auto/api/ParticleMeteor.lua | 11 | 1380 |
--------------------------------
-- @module ParticleMeteor
-- @extend ParticleSystemQuad
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ParticleMeteor] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ParticleMeteor] initWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Create a meteor particle system.<br>
-- return An autoreleased ParticleMeteor object.
-- @function [parent=#ParticleMeteor] create
-- @param self
-- @return ParticleMeteor#ParticleMeteor ret (return value: cc.ParticleMeteor)
--------------------------------
-- Create a meteor particle system withe a fixed number of particles.<br>
-- param numberOfParticles A given number of particles.<br>
-- return An autoreleased ParticleMeteor object.<br>
-- js NA
-- @function [parent=#ParticleMeteor] createWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return ParticleMeteor#ParticleMeteor ret (return value: cc.ParticleMeteor)
--------------------------------
-- js ctor
-- @function [parent=#ParticleMeteor] ParticleMeteor
-- @param self
-- @return ParticleMeteor#ParticleMeteor self (return value: cc.ParticleMeteor)
return nil
| mit |
shodoco/bcc | tests/lua/test_uprobes.lua | 4 | 1645 | local suite = require("test_helper")
local ffi = require("ffi")
local TestUprobes = {}
ffi.cdef[[
int getpid(void);
void malloc_stats(void);
]]
function TestUprobes:test_simple_library()
local text = [[
#include <uapi/linux/ptrace.h>
BPF_ARRAY(stats, u64, 1);
static void incr(int idx) {
u64 *ptr = stats.lookup(&idx);
if (ptr)
++(*ptr);
}
int count(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid();
if (pid == PID)
incr(0);
return 0;
}]]
local pid = tonumber(ffi.C.getpid())
local text = text:gsub("PID", tostring(pid))
local b = BPF:new{text=text}
b:attach_uprobe{name="c", sym="malloc_stats", fn_name="count", pid=pid}
b:attach_uprobe{name="c", sym="malloc_stats", fn_name="count", pid=pid, retprobe=true}
assert_equals(BPF.num_open_uprobes(), 2)
ffi.C.malloc_stats()
local stats = b:get_table("stats")
assert_equals(tonumber(stats:get(0)), 2)
end
function TestUprobes:test_simple_binary()
local text = [[
#include <uapi/linux/ptrace.h>
BPF_ARRAY(stats, u64, 1);
static void incr(int idx) {
u64 *ptr = stats.lookup(&idx);
if (ptr)
++(*ptr);
}
int count(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid();
incr(0);
return 0;
}]]
local b = BPF:new{text=text}
b:attach_uprobe{name="/usr/bin/python", sym="main", fn_name="count"}
b:attach_uprobe{name="/usr/bin/python", sym="main", fn_name="count", retprobe=true}
os.spawn("/usr/bin/python -V")
local stats = b:get_table("stats")
assert_true(tonumber(stats:get(0)) >= 2)
end
function TestUprobes:teardown()
BPF.cleanup()
end
suite("TestUprobes", TestUprobes)
| apache-2.0 |
Armyluix/darkstar | scripts/zones/Sealions_Den/npcs/_0w0.lua | 12 | 1945 | -----------------------------------
-- Area: Sealion's Den
-- NPC: Iron Gate
-- @pos 612 132 774 32
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/globals/titles");
require("scripts/globals/teleports");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x000D);
elseif (EventTriggerBCNM(player,npc)) then
return;
elseif (player:getCurrentMission(COP) > THE_WARRIOR_S_PATH) then
player:startEvent(0x000C);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
EventUpdateBCNM(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
if (csid == 0x000c and option == 1) then
toPalaceEntrance(player);
elseif (csid == 0x000D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,SLANDEROUS_UTTERINGS);
player:addMission(COP,THE_ENDURING_TUMULT_OF_WAR);
player:addTitle(THE_LOST_ONE);
end
end; | gpl-3.0 |
rigeirani/oto | plugins/dice.lua | 16 | 1228 | local command = 'roll <nDr>'
local doc = [[```
/roll <nDr>
Returns a set of dice rolls, where n is the number of rolls and r is the range. If only a range is given, returns only one roll.
```]]
local triggers = {
'^/roll[@'..bot.username..']*'
}
local action = function(msg)
local input = msg.text_lower:input()
if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
local count, range
if input:match('^[%d]+d[%d]+$') then
count, range = input:match('([%d]+)d([%d]+)')
elseif input:match('^d?[%d]+$') then
count = 1
range = input:match('^d?([%d]+)$')
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
count = tonumber(count)
range = tonumber(range)
if range < 2 then
sendReply(msg, 'The minimum range is 2.')
return
end
if range > 1000 or count > 1000 then
sendReply(msg, 'The maximum range and count are 1000.')
return
end
local output = '*' .. count .. 'd' .. range .. '*\n`'
for i = 1, count do
output = output .. math.random(range) .. '\t'
end
output = output .. '`'
sendMessage(msg.chat.id, output, true, msg.message_id, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
| gpl-2.0 |
ennorehling/tolua | src/bin/lua/enumerate.lua | 14 | 1815 | -- tolua: enumerate class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: enumerate.lua,v 1.3 2009/11/24 16:45:13 fabraham Exp $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Enumerate class
-- Represents enumeration
-- The following fields are stored:
-- {i} = list of constant names
classEnumerate = {
}
classEnumerate.__index = classEnumerate
setmetatable(classEnumerate,classFeature)
-- register enumeration
function classEnumerate:register ()
local nspace = getnamespace(classContainer.curr)
local i=1
while self[i] do
output(' tolua_constant(tolua_S,"'..self.lnames[i]..'",'..nspace..self[i]..');')
i = i+1
end
end
-- Print method
function classEnumerate:print (ident,close)
print(ident.."Enumerate{")
print(ident.." name = "..self.name)
local i=1
while self[i] do
print(ident.." '"..self[i].."'("..self.lnames[i].."),")
i = i+1
end
print(ident.."}"..close)
end
-- Internal constructor
function _Enumerate (t)
setmetatable(t,classEnumerate)
append(t)
appendenum(t)
return t
end
-- Constructor
-- Expects a string representing the enumerate body
function Enumerate (n,b)
local t = split(strsub(b,2,-2),',') -- eliminate braces
local i = 1
local e = {n=0}
while t[i] do
local tt = split(t[i],'=') -- discard initial value
e.n = e.n + 1
e[e.n] = tt[1]
i = i+1
end
-- set lua names
i = 1
e.lnames = {}
while e[i] do
local t = split(e[i],'@')
e[i] = t[1]
if not t[2] then
t[2] = applyrenaming(t[1])
end
e.lnames[i] = t[2] or t[1]
i = i+1
end
e.name = n
if n~="" then
Typedef("int "..n)
end
return _Enumerate(e)
end
| mit |
Armyluix/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm3.lua | 16 | 1199 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Armed Gears(ZNM T3))
-- @pos -42 -4 -169 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(2574,1) and trade:getItemCount() == 1) then -- Trade Ferrite
player:tradeComplete();
SpawnMob(17072178,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
Armyluix/darkstar | scripts/globals/spells/bluemagic/temporal_shift.lua | 18 | 1436 | -----------------------------------------
-- Spell: Temporal Shift
-- Enemies within range are temporarily prevented from acting
-- Spell cost: 48 MP
-- Monster Type: Luminians
-- Spell Type: Magical (Lightning)
-- Blue Magic Points: 5
-- Stat Bonus: HP+10, MP+15
-- Level: 73
-- Casting Time: 0.5 seconds
-- Recast Time: 120 seconds
-- Magic Bursts on: Impaction, Fragmentation, and Light
-- Combos: Attack Bonus
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_STUN;
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,EFFECT_STUN);
local duration = 5 * resist;
if (resist > 0.0625) then -- Do it!
if (target:addStatusEffect(typeEffect,2,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end;
return typeEffect;
end;
| gpl-3.0 |
Armyluix/darkstar | scripts/zones/Quicksand_Caves/npcs/qm7.lua | 17 | 1904 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: ???
-- Involved in Mission: The Mithra and the Crystal (Zilart 12)
-- @pos -504 20 -419 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == THE_MITHRA_AND_THE_CRYSTAL and player:getVar("ZilartStatus") == 1 and player:hasKeyItem(SCRAP_OF_PAPYRUS) == false) then
if (player:needToZone() and player:getVar("AncientVesselKilled") == 1) then
player:setVar("AncientVesselKilled",0);
player:addKeyItem(SCRAP_OF_PAPYRUS);
player:messageSpecial(KEYITEM_OBTAINED,SCRAP_OF_PAPYRUS);
else
player:startEvent(0x000c);
end
elseif (player:hasCompletedMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL) or player:hasKeyItem(SCRAP_OF_PAPYRUS)) then
player:messageSpecial(YOU_FIND_NOTHING);
else
player:messageSpecial(SOMETHING_IS_BURIED);
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 == 0x000c and option == 1) then
SpawnMob(17629642,600):updateClaim(player); -- Ancient Vessel
end
end; | gpl-3.0 |
Armyluix/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/qm2.lua | 24 | 2318 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- NPC: ??? (Ix'aern (Dark Knight) Spawn)
-- Allows players to spawn the Ix'aern (Dark Knight) by checking ??? only after killing the required mobs in the same room as the ???.
-- @pos ,-560 5 239
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/zones/The_Garden_of_RuHmet/MobIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
Kills = GetServerVariable("[PH]Ix_aern_drk");
--print(Kills)
moba = GetMobByID(16921018);
mobb = GetMobByID(16921019);
mobc = GetMobByID(16921020);
if (Kills == 0) then
player:messageSpecial(UNKNOWN_PRESENCE);
elseif (Kills == 1) then
player:messageSpecial(NONE_HOSTILE);
elseif (Kills == 2) then
player:messageSpecial(NONE_HOSTILE);--(SHEER_ANIMOSITY);
elseif (Kills == 3) then
moba:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos.
SpawnMob(16921018,180):updateClaim(player);
mobb:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos.
SpawnMob(16921019,180):updateClaim(player);
mobc:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos.
SpawnMob(16921020,180):updateClaim(player);
GetNPCByID(16921028):hideNPC(900);
if (math.random(0,1) == 1) then -- random do select which item do drop. Will select one item 100% of the time.
SetDropRate(4397,1854,000);
else
SetDropRate(4397,1902,000);
end
end
]]--
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Nashmau/npcs/Pipiroon.lua | 17 | 1224 | -----------------------------------
-- Area: Nashmau
-- NPC: Pipiroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIPIROON_SHOP_DIALOG);
stock = {0x43A1,1204, -- Grenade
0x43A3,6000, -- Riot Grenade
0x03A0,515, -- Bomb Ash
0x0b39,10000} -- Nashmau Waystone
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
dios-game/dios-cocos | src/apps/lua-tests/Resources/src/IntervalTest/IntervalTest.lua | 17 | 4556 | local scheduler = cc.Director:getInstance():getScheduler()
local SID_STEP1 = 100
local SID_STEP2 = 101
local SID_STEP3 = 102
local IDC_PAUSE = 200
local function IntervalLayer()
local ret = cc.Layer:create()
local m_time0 = 0
local m_time1 = 0
local m_time2 = 0
local m_time3 = 0
local m_time4 = 0
local s = cc.Director:getInstance():getWinSize()
-- sun
local sun = cc.ParticleSun:create()
sun:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png"))
sun:setPosition( cc.p(VisibleRect:rightTop().x-32,VisibleRect:rightTop().y-32) )
sun:setTotalParticles(130)
sun:setLife(0.6)
ret:addChild(sun)
-- timers
m_label0 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label0:setAnchorPoint(cc.p(0.5, 0.5))
m_label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label1:setAnchorPoint(cc.p(0.5, 0.5))
m_label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label2:setAnchorPoint(cc.p(0.5, 0.5))
m_label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label3:setAnchorPoint(cc.p(0.5, 0.5))
m_label4 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label4:setAnchorPoint(cc.p(0.5, 0.5))
local function update(dt)
m_time0 = m_time0 + dt
local str = string.format("%2.1f", m_time0)
m_label0:setString(str)
end
ret:scheduleUpdateWithPriorityLua(update, 0)
local function step1(dt)
m_time1 = m_time1 + dt
local str = string.format("%2.1f", m_time1)
m_label1:setString( str )
end
local function step2(dt)
m_time2 = m_time2 + dt
local str = string.format("%2.1f", m_time2)
m_label2:setString( str )
end
local function step3(dt)
m_time3 = m_time3 + dt
local str = string.format("%2.1f", m_time3)
m_label3:setString( str )
end
local function step4(dt)
m_time4 = m_time4 + dt
local str = string.format("%2.1f", m_time4)
m_label4:setString( str )
end
local schedulerEntry1 = nil
local schedulerEntry2 = nil
local schedulerEntry3 = nil
local schedulerEntry4 = nil
local function onNodeEvent(event)
if event == "enter" then
schedulerEntry1 = scheduler:scheduleScriptFunc(step1, 0, false)
schedulerEntry2 = scheduler:scheduleScriptFunc(step2, 0, false)
schedulerEntry3 = scheduler:scheduleScriptFunc(step3, 1.0, false)
schedulerEntry4 = scheduler:scheduleScriptFunc(step4, 2.0, false)
elseif event == "exit" then
scheduler:unscheduleScriptEntry(schedulerEntry1)
scheduler:unscheduleScriptEntry(schedulerEntry2)
scheduler:unscheduleScriptEntry(schedulerEntry3)
scheduler:unscheduleScriptEntry(schedulerEntry4)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
end
end
end
ret:registerScriptHandler(onNodeEvent)
m_label0:setPosition(cc.p(s.width*1/6, s.height/2))
m_label1:setPosition(cc.p(s.width*2/6, s.height/2))
m_label2:setPosition(cc.p(s.width*3/6, s.height/2))
m_label3:setPosition(cc.p(s.width*4/6, s.height/2))
m_label4:setPosition(cc.p(s.width*5/6, s.height/2))
ret:addChild(m_label0)
ret:addChild(m_label1)
ret:addChild(m_label2)
ret:addChild(m_label3)
ret:addChild(m_label4)
-- Sprite
local sprite = cc.Sprite:create(s_pPathGrossini)
sprite:setPosition( cc.p(VisibleRect:left().x + 40, VisibleRect:bottom().y + 50) )
local jump = cc.JumpBy:create(3, cc.p(s.width-80,0), 50, 4)
ret:addChild(sprite)
sprite:runAction( cc.RepeatForever:create(cc.Sequence:create(jump, jump:reverse())))
-- pause button
local item1 = cc.MenuItemFont:create("Pause")
local function onPause(tag, pSender)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
else
cc.Director:getInstance():pause()
end
end
item1:registerScriptTapHandler(onPause)
local menu = cc.Menu:create(item1)
menu:setPosition( cc.p(s.width/2, s.height-50) )
ret:addChild( menu )
return ret
end
function IntervalTestMain()
cclog("IntervalTestMain")
local scene = cc.Scene:create()
local layer = IntervalLayer()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tests/lua-tests/src/IntervalTest/IntervalTest.lua | 17 | 4556 | local scheduler = cc.Director:getInstance():getScheduler()
local SID_STEP1 = 100
local SID_STEP2 = 101
local SID_STEP3 = 102
local IDC_PAUSE = 200
local function IntervalLayer()
local ret = cc.Layer:create()
local m_time0 = 0
local m_time1 = 0
local m_time2 = 0
local m_time3 = 0
local m_time4 = 0
local s = cc.Director:getInstance():getWinSize()
-- sun
local sun = cc.ParticleSun:create()
sun:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png"))
sun:setPosition( cc.p(VisibleRect:rightTop().x-32,VisibleRect:rightTop().y-32) )
sun:setTotalParticles(130)
sun:setLife(0.6)
ret:addChild(sun)
-- timers
m_label0 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label0:setAnchorPoint(cc.p(0.5, 0.5))
m_label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label1:setAnchorPoint(cc.p(0.5, 0.5))
m_label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label2:setAnchorPoint(cc.p(0.5, 0.5))
m_label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label3:setAnchorPoint(cc.p(0.5, 0.5))
m_label4 = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "0")
m_label4:setAnchorPoint(cc.p(0.5, 0.5))
local function update(dt)
m_time0 = m_time0 + dt
local str = string.format("%2.1f", m_time0)
m_label0:setString(str)
end
ret:scheduleUpdateWithPriorityLua(update, 0)
local function step1(dt)
m_time1 = m_time1 + dt
local str = string.format("%2.1f", m_time1)
m_label1:setString( str )
end
local function step2(dt)
m_time2 = m_time2 + dt
local str = string.format("%2.1f", m_time2)
m_label2:setString( str )
end
local function step3(dt)
m_time3 = m_time3 + dt
local str = string.format("%2.1f", m_time3)
m_label3:setString( str )
end
local function step4(dt)
m_time4 = m_time4 + dt
local str = string.format("%2.1f", m_time4)
m_label4:setString( str )
end
local schedulerEntry1 = nil
local schedulerEntry2 = nil
local schedulerEntry3 = nil
local schedulerEntry4 = nil
local function onNodeEvent(event)
if event == "enter" then
schedulerEntry1 = scheduler:scheduleScriptFunc(step1, 0, false)
schedulerEntry2 = scheduler:scheduleScriptFunc(step2, 0, false)
schedulerEntry3 = scheduler:scheduleScriptFunc(step3, 1.0, false)
schedulerEntry4 = scheduler:scheduleScriptFunc(step4, 2.0, false)
elseif event == "exit" then
scheduler:unscheduleScriptEntry(schedulerEntry1)
scheduler:unscheduleScriptEntry(schedulerEntry2)
scheduler:unscheduleScriptEntry(schedulerEntry3)
scheduler:unscheduleScriptEntry(schedulerEntry4)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
end
end
end
ret:registerScriptHandler(onNodeEvent)
m_label0:setPosition(cc.p(s.width*1/6, s.height/2))
m_label1:setPosition(cc.p(s.width*2/6, s.height/2))
m_label2:setPosition(cc.p(s.width*3/6, s.height/2))
m_label3:setPosition(cc.p(s.width*4/6, s.height/2))
m_label4:setPosition(cc.p(s.width*5/6, s.height/2))
ret:addChild(m_label0)
ret:addChild(m_label1)
ret:addChild(m_label2)
ret:addChild(m_label3)
ret:addChild(m_label4)
-- Sprite
local sprite = cc.Sprite:create(s_pPathGrossini)
sprite:setPosition( cc.p(VisibleRect:left().x + 40, VisibleRect:bottom().y + 50) )
local jump = cc.JumpBy:create(3, cc.p(s.width-80,0), 50, 4)
ret:addChild(sprite)
sprite:runAction( cc.RepeatForever:create(cc.Sequence:create(jump, jump:reverse())))
-- pause button
local item1 = cc.MenuItemFont:create("Pause")
local function onPause(tag, pSender)
if cc.Director:getInstance():isPaused() then
cc.Director:getInstance():resume()
else
cc.Director:getInstance():pause()
end
end
item1:registerScriptTapHandler(onPause)
local menu = cc.Menu:create(item1)
menu:setPosition( cc.p(s.width/2, s.height-50) )
ret:addChild( menu )
return ret
end
function IntervalTestMain()
cclog("IntervalTestMain")
local scene = cc.Scene:create()
local layer = IntervalLayer()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
Armyluix/darkstar | scripts/zones/Sacrarium/npcs/qm3.lua | 17 | 1738 | -----------------------------------
-- Area: Sacrarium
-- NPC: qm3 (???)
-- Notes: Used to spawn Old Prof. Mariselle
-- @pos 62.668 -3.111 127.288 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OldProfessor = 16891970;
if (GetServerVariable("Old_Prof_Spawn_Location") == 3) then
if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then
player:messageSpecial(EVIL_PRESENCE);
SpawnMob(OldProfessor,300):updateClaim(player);
GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC
else
player:messageSpecial(DRAWER_SHUT);
end
elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(DRAWER_OPEN);
player:messageSpecial(DRAWER_EMPTY);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
urueedi/luci | modules/luci-base/luasrc/sys/zoneinfo/tzoffset.lua | 14 | 4023 | -- Licensed to the public under the Apache License 2.0.
module "luci.sys.zoneinfo.tzoffset"
OFFSET = {
gmt = 0, -- GMT
eat = 10800, -- EAT
cet = 3600, -- CET
wat = 3600, -- WAT
cat = 7200, -- CAT
eet = 7200, -- EET
wet = 0, -- WET
sast = 7200, -- SAST
hst = -36000, -- HST
hdt = -32400, -- HDT
akst = -32400, -- AKST
akdt = -28800, -- AKDT
ast = -14400, -- AST
brt = -10800, -- BRT
art = -10800, -- ART
pyt = -14400, -- PYT
pyst = -10800, -- PYST
est = -18000, -- EST
cst = -21600, -- CST
cdt = -18000, -- CDT
amt = -14400, -- AMT
cot = -18000, -- COT
mst = -25200, -- MST
mdt = -21600, -- MDT
vet = -16200, -- VET
gft = -10800, -- GFT
pst = -28800, -- PST
pdt = -25200, -- PDT
act = -18000, -- ACT
wgt = -10800, -- WGT
wgst = -7200, -- WGST
ect = -18000, -- ECT
gyt = -14400, -- GYT
bot = -14400, -- BOT
pet = -18000, -- PET
pmst = -10800, -- PMST
pmdt = -7200, -- PMDT
uyt = -10800, -- UYT
fnt = -7200, -- FNT
srt = -10800, -- SRT
clt = -10800, -- CLT
egt = -3600, -- EGT
egst = 0, -- EGST
nst = -12600, -- NST
ndt = -9000, -- NDT
awst = 28800, -- AWST
davt = 25200, -- DAVT
ddut = 36000, -- DDUT
mist = 39600, -- MIST
mawt = 18000, -- MAWT
nzst = 43200, -- NZST
nzdt = 46800, -- NZDT
rott = -10800, -- ROTT
syot = 10800, -- SYOT
utc = 0, -- UTC
vost = 21600, -- VOST
almt = 21600, -- ALMT
anat = 43200, -- ANAT
aqtt = 18000, -- AQTT
tmt = 18000, -- TMT
azt = 14400, -- AZT
azst = 18000, -- AZST
ict = 25200, -- ICT
kgt = 21600, -- KGT
bnt = 28800, -- BNT
irkt = 28800, -- IRKT
chot = 28800, -- CHOT
chost = 32400, -- CHOST
ist = 19800, -- IST
bdt = 21600, -- BDT
tlt = 32400, -- TLT
gst = 14400, -- GST
tjt = 18000, -- TJT
hkt = 28800, -- HKT
hovt = 25200, -- HOVT
hovst = 28800, -- HOVST
wib = 25200, -- WIB
wit = 32400, -- WIT
aft = 16200, -- AFT
pett = 43200, -- PETT
pkt = 18000, -- PKT
npt = 20700, -- NPT
yakt = 32400, -- YAKT
krat = 25200, -- KRAT
myt = 28800, -- MYT
magt = 36000, -- MAGT
wita = 28800, -- WITA
pht = 28800, -- PHT
novt = 21600, -- NOVT
omst = 21600, -- OMST
orat = 18000, -- ORAT
kst = 30600, -- KST
qyzt = 21600, -- QYZT
mmt = 23400, -- MMT
sakt = 36000, -- SAKT
uzt = 18000, -- UZT
sgt = 28800, -- SGT
sret = 39600, -- SRET
get = 14400, -- GET
btt = 21600, -- BTT
jst = 32400, -- JST
ulat = 28800, -- ULAT
ulast = 32400, -- ULAST
xjt = 21600, -- XJT
vlat = 36000, -- VLAT
yekt = 18000, -- YEKT
azot = -3600, -- AZOT
azost = 0, -- AZOST
cvt = -3600, -- CVT
fkst = -10800, -- FKST
acst = 34200, -- ACST
acdt = 37800, -- ACDT
aest = 36000, -- AEST
acwst = 31500, -- ACWST
lhst = 37800, -- LHST
lhdt = 39600, -- LHDT
msk = 10800, -- MSK
samt = 14400, -- SAMT
iot = 21600, -- IOT
cxt = 25200, -- CXT
cct = 23400, -- CCT
tft = 18000, -- TFT
sct = 14400, -- SCT
mvt = 18000, -- MVT
mut = 14400, -- MUT
ret = 14400, -- RET
wsst = 46800, -- WSST
wsdt = 50400, -- WSDT
bst = 39600, -- BST
chast = 45900, -- CHAST
chadt = 49500, -- CHADT
chut = 36000, -- CHUT
east = -18000, -- EAST
vut = 39600, -- VUT
phot = 46800, -- PHOT
tkt = 46800, -- TKT
fjt = 43200, -- FJT
fjst = 46800, -- FJST
tvt = 43200, -- TVT
galt = -21600, -- GALT
gamt = -32400, -- GAMT
sbt = 39600, -- SBT
lint = 50400, -- LINT
kost = 39600, -- KOST
mht = 43200, -- MHT
mart = -34200, -- MART
sst = -39600, -- SST
nrt = 43200, -- NRT
nut = -39600, -- NUT
nft = 39600, -- NFT
nct = 39600, -- NCT
pwt = 32400, -- PWT
pont = 39600, -- PONT
pgt = 36000, -- PGT
ckt = -36000, -- CKT
taht = -36000, -- TAHT
gilt = 43200, -- GILT
tot = 46800, -- TOT
wakt = 43200, -- WAKT
wft = 43200, -- WFT
}
| apache-2.0 |
abriasffxi/darkstar | scripts/globals/spells/gravity_ii.lua | 27 | 1102 | -----------------------------------------
-- Spell: Gravity II
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- Pull base stats.
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
local power = 60; -- 60% reduction
-- Duration, including resistance. Unconfirmed.
local duration = 180 * applyResistanceEffect(caster,spell,target,dINT,35,0,EFFECT_WEIGHT);
if (duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if (target:addStatusEffect(EFFECT_WEIGHT,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(284);
end
return EFFECT_WEIGHT;
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/globals/items/marinara_pizza.lua | 18 | 1599 | -----------------------------------------
-- ID: 5743
-- Item: marinara_pizza
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Health Points 20
-- Attack +20% (cap 50 @ 250 base attack)
-- Accuracy +10% (54)
-- Undead Killer
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5743);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 50);
target:addMod(MOD_FOOD_ACCP, 10);
target:addMod(MOD_FOOD_ACC_CAP, 54);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 50);
target:delMod(MOD_FOOD_ACCP, 10);
target:delMod(MOD_FOOD_ACC_CAP, 54);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/tests/lua-tests/src/ByteCodeEncryptTest/ByteCodeEncryptTest.lua | 4 | 3906 | local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local is64BitIOSDevice = cc.Application:getInstance():is64BitIOSDevice()
if cc.PLATFORM_OS_LINUX ~= targetPlatform and is64BitIOSDevice ~= true then
require("ByteCodeEncryptTest/ByteCodeTest")
require("ByteCodeEncryptTest/ByteCodeAndEncryptTest")
end
if (cc.PLATFORM_OS_IPHONE == targetPlatform or cc.PLATFORM_OS_IPAD == targetPlatform) and is64BitIOSDevice == true then
require("ByteCodeEncryptTest/ByteCodeAndEncryptTest-arm64")
require("ByteCodeEncryptTest/ByteCodeTest-arm64")
end
local LINE_SPACE = 40
local ItemTagBasic = 1000
local ByteCodeEncryptEnum =
{
TEST_BYTECODE = 0,
TEST_BYTECODE_ENCRYPT = 1,
TEST_MAX_COUNT = 2,
}
local TestsName =
{
"ByteCodeFileTest",
"ByteCodeAndEncryptFileTest",
}
local CreateByteCodeEncryptTestTable =
{
runByteCodeFileTest,
runByteCodeAndEncryptFileTest,
}
local function byteCodeEncryptMainLayer()
local size = cc.Director:getInstance():getWinSize()
local function createByteCodeEncryptTestScene(index)
local newScene = CreateByteCodeEncryptTestTable[index]()
return newScene
end
local function menuCallback(tag, sender)
local scene = nil
local index = sender:getLocalZOrder() - ItemTagBasic
local byteCodeEncryptScene = createByteCodeEncryptTestScene(index)
if nil ~= byteCodeEncryptScene then
cc.Director:getInstance():replaceScene(byteCodeEncryptScene)
end
end
local layer = cc.Layer:create()
local menu = cc.Menu:create()
menu:setPosition(cc.p(0, 0))
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
for i = 1, ByteCodeEncryptEnum.TEST_MAX_COUNT do
local item = cc.MenuItemFont:create(TestsName[i])
item:registerScriptTapHandler(menuCallback)
item:setPosition(size.width / 2, size.height - i * LINE_SPACE)
menu:addChild(item, ItemTagBasic + i)
if cc.PLATFORM_OS_LINUX == targetPlatform or is64BitIOSDevice == true then -- isIOS64bit
item:setEnabled(false)
end
if (cc.PLATFORM_OS_IPHONE == targetPlatform or cc.PLATFORM_OS_IPAD == targetPlatform) and is64BitIOSDevice == true then
item:setEnabled(true)
end
end
layer:addChild(menu)
-- handling touch events
local beginPos = {x = 0, y = 0}
local function onTouchesBegan(touches, event)
beginPos = touches[1]:getLocation()
end
local function onTouchesMoved(touches, event)
local location = touches[1]:getLocation()
local nMoveY = location.y - beginPos.y
local curPosx, curPosy = menu:getPosition()
local nextPosy = curPosy + nMoveY
local winSize = cc.Director:getInstance():getWinSize()
if nextPosy < 0 then
menu:setPosition(0, 0)
return
end
if nextPosy > ((ByteCodeEncryptEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height) then
menu:setPosition(0, ((ByteCodeEncryptEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height))
return
end
menu:setPosition(curPosx, nextPosy)
beginPos = {x = location.x, y = location.y}
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN )
listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCH_MOVED )
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)
return layer
end
-------------------------------------
-- ByteCodeEncrypt Test
-------------------------------------
function ByteCodeEncryptTestMain()
local scene = cc.Scene:create()
scene:addChild(byteCodeEncryptMainLayer())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
abriasffxi/darkstar | scripts/zones/Abyssea-Konschtat/mobs/Turul.lua | 17 | 2144 | -----------------------------------
-- Area: Abyssea - Konschtat (15)
-- Mob: Turul
-----------------------------------
require("scripts/globals/status");
mixins = { require("scripts/mixins/families/amphiptere") }
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob, target)
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
-- Uncertain of threshold. Going with 50% for now.
-- (possibly varies, perhaps is simply lower HP = greater cast chance?)
if (mob:getHPP() <=50) then
mob:setMobMod(MOBMOD_SPELL_LIST, 175);
else
-- I'm assuming that if it heals up, it goes back to the other spell list.
mob:setMobMod(MOBMOD_SPELL_LIST, 174);
-- This 'else' can be removed if that isn't the case, and a localVar added so it only execs once.
end
end;
------------------------------------
-- onSpellPrecast
------------------------------------
function onSpellPrecast(mob, spell)
--[[
Todo:
"Turul will often cast Thunder based spells on itself to recover HP."
One way of handling this would be treating ele nuke heals like we do melee special (use its own list)
and setting absorb element 100% chance. This would let us use the AI's already existing "heal chance"
https://github.com/DarkstarProject/darkstar/blob/638b9018e563f98ceddf05d642b6e3db055ccc36/src/map/mob_spell_container.cpp#L124
]]
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
end;
| gpl-3.0 |
rdlaitila/LURE | src/__legacy__/rom/__legacy__/objects/lure_rom_nodelist.lua | 1 | 3584 | lure.rom.nodeListObj = {}
-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function lure.rom.nodeListObj.new()
local self = {}
local self_mt = {}
setmetatable(self, self_mt)
--===================================================================
-- OBJECT METATABLE =
--===================================================================
self_mt.__tostring = function(t)
return "[object]:NodeList"
end
---------------------------------------------------------------------
self_mt.__index = function(t,k)
local mutatorfound = false
if rawget(t,"mutators") then
for i,v in pairs( t.mutators ) do -- loop through the mutators table to see if we can match a getter
if ( "GET"..tostring( k ):upper() ) == i:upper() then
return t.mutators[i]()
end
end
end
if mutatorfound == false then
if type(k) == "number" then
return self.item(k)
else
return rawget(t,k) --if no mutator found, simply return the rawget key if exists
end
end
end
---------------------------------------------------------------------
self_mt.__newindex = function(t,k,v)
local mutatorfound = false
local mutatorkey = "SET"..k:upper()
if rawget(t, "mutators") then
for key in pairs(t.mutators) do -- loop through the mutators table to see if we can match a setter
if key:upper() == mutatorkey then
t.mutators[key](v)
mutatorfound = true
end
end
end
if mutatorfound == false then
rawset(t,k,v) --if no mutator found, simply rawset the key and value
end
end
---------------------------------------------------------------------
--===================================================================
-- MUTATORS =
--===================================================================
self.mutators = {}
---------------------------------------------------------------------
self.mutators.getLength = function()
return table.getn(self.nodes)
end
---------------------------------------------------------------------
self.mutators.setLength = function()
lure.throw(4, "Cannot set length property on object: '".. tostring(self) .. "'. Reason: NOT_ALLOWED")
end
---------------------------------------------------------------------
-- PROPERTIES -------------------------------------------------------
self.nodes = {}
---------------------------------------------------------------------
-- METHODS ----------------------------------------------------------
self.item = function(pIndex)
return self.nodes[pIndex]
end
---------------------------------------------------------------------
self.addItem = function(pNodeObj)
table.insert(self.nodes, pNodeObj)
return pNodeObj
end
---------------------------------------------------------------------
self.removeItem = function(pNodeObj)
if self.length > 0 then
for k, v in ipairs(self.nodes) do
if self.nodes[k] == pNodeObj then
local oldNode = self.nodes[k]
table.remove(self.nodes, k)
return oldNode
end
end
end
end
---------------------------------------------------------------------
self.getNodeIndex = function( pNode )
for a=1, table.getn(self.nodes) do
if self.nodes[a] == pNode then
return a
end
end
return nil
end
---------------------------------------------------------------------
return self
end
-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | mit |
Armyluix/darkstar | scripts/zones/Lower_Delkfutts_Tower/npcs/Grounds_Tome.lua | 34 | 1149 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_LOWER_DELKFUTTS_TOWER,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,777,778,779,780,781,0,0,0,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,777,778,779,780,781,0,0,0,0,0,GOV_MSG_LOWER_DELKFUTTS_TOWER);
end;
| gpl-3.0 |
Armyluix/darkstar | scripts/globals/effects/magic_shield.lua | 17 | 1752 | -----------------------------------
--
-- Magic Shield BLOCKS all magic attacks
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if (effect:getPower() == 3) then -- arcane stomp
target:addMod(MOD_FIRE_ABSORB, 100);
target:addMod(MOD_EARTH_ABSORB, 100);
target:addMod(MOD_WATER_ABSORB, 100);
target:addMod(MOD_WIND_ABSORB, 100);
target:addMod(MOD_ICE_ABSORB, 100);
target:addMod(MOD_LTNG_ABSORB, 100);
target:addMod(MOD_LIGHT_ABSORB, 100);
target:addMod(MOD_DARK_ABSORB, 100);
elseif (effect:getPower() < 2) then
target:addMod(MOD_UDMGMAGIC, -256);
else
target:addMod(MOD_MAGIC_ABSORB, 100);
end;
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
if (effect:getPower() == 3) then -- arcane stomp
target:delMod(MOD_FIRE_ABSORB, 100);
target:delMod(MOD_EARTH_ABSORB, 100);
target:delMod(MOD_WATER_ABSORB, 100);
target:delMod(MOD_WIND_ABSORB, 100);
target:delMod(MOD_ICE_ABSORB, 100);
target:delMod(MOD_LTNG_ABSORB, 100);
target:delMod(MOD_LIGHT_ABSORB, 100);
target:delMod(MOD_DARK_ABSORB, 100);
elseif (effect:getPower() < 2) then
target:delMod(MOD_UDMGMAGIC, -256);
else
target:delMod(MOD_MAGIC_ABSORB, 100);
end;
end; | gpl-3.0 |
Armyluix/darkstar | scripts/zones/Bastok_Markets/TextIDs.lua | 9 | 5351 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; --Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6383; --Try trading again after sorting your inventory.
ITEM_OBTAINED = 6384; --Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>
GIL_OBTAINED = 6385; --Obtained <<<Numeric Parameter 0>>> gil.
KEYITEM_OBTAINED = 6387; --Obtained key item: <<<Unknown Parameter (Type: 80) 1>>>
NOT_HAVE_ENOUGH_GIL = 6389; --You do not have enough gil.
ITEMS_OBTAINED = 6393; --You obtain ?Numeric Parameter 1? ?Possible Special Code: 01??Speaker Name?)??BAD CHAR: 80??BAD CHAR: 80??BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?!?Prompt?
HOMEPOINT_SET = 6473; --Home point set!
GOLDSMITHING_SUPPORT = 7058; --Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ...
GUILD_TERMINATE_CONTRACT = 7072; --You have terminated your trading contract with the ?Multiple Choice (Parameter 1)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
GUILD_NEW_CONTRACT = 7080; --You have formed a new trading contract with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
NO_MORE_GP_ELIGIBLE = 7087; --You are not eligible to receive guild points at this time.
GP_OBTAINED = 7076; --Obtained <<<Numeric Parameter 0>>> guild points.
NOT_HAVE_ENOUGH_GP = 7093; --You do not have enough guild points.
FISHING_MESSAGE_OFFSET = 7187; --You can't fish here.
-- Conquest System
CONQUEST = 7754; --You've earned conquest points!
-- Mission Dialogs
YOU_ACCEPT_THE_MISSION = 6494; --You have accepted the mission.
ORIGINAL_MISSION_OFFSET = 6499; -- You can consult the ission section of the main menu to review your objectives. Speed and efficiency are your priorities. Dismissed.
EXTENDED_MISSION_OFFSET = 8116; --Go to Ore Street and talk to Medicine Eagle. He says he was there when the commotion started.
-- Other Dialogs
ITEM_DELIVERY_DIALOG = 7637; --Need something sent to a friend's house? Sending items to your own room? You've come to the right place
-- Harvest Festival
TRICK_OR_TREAT = 8239; --Trick or treat...
THANK_YOU_TREAT = 8240; --And now for your treat...
HERE_TAKE_THIS = 8241; --Here, take this...
IF_YOU_WEAR_THIS = 8242; --If you put this on and walk around, something...unexpected might happen...
THANK_YOU = 8240; --Thank you...
-- Shop Texts
SOMNPAEMN_CLOSED_DIALOG = 7548; --I'm trying to start a business selling goods from Sarutabaruta,
YAFAFA_CLOSED_DIALOG = 7549; --I'm trying to start a business selling goods from Kolshushu,
OGGODETT_CLOSED_DIALOG = 7550; --I'm trying to start a business selling goods from Aragoneu,
TEERTH_SHOP_DIALOG = 7651; --Welcome to the Goldsmiths' Guild shop. What can I do for you?
VISALA_SHOP_DIALOG = 7652; --Welcome to the Goldsmiths' Guild shop. How may I help you?
ZHIKKOM_SHOP_DIALOG = 7653; --Welcome to the only weaponry store in Bastok, the Dragon's Claws!
CIQALA_SHOP_DIALOG = 7654; --A weapon is the most precious thing to an adventurer! Well, after his life, of course.
PERITRAGE_SHOP_DIALOG = 7655; --Hey! I've got just the thing for you!
BRUNHILDE_SHOP_DIALOG = 7656; --Welcome to my store! You want armor, you want shields? I've got them all!
CHARGINGCHOKOBO_SHOP_DIALOG = 7657; --Hello. What piece of armor are you missing?
BALTHILDA_SHOP_DIALOG = 7658; --Feeling defenseless of late? Brunhilde's Armory has got you covered!
MJOLL_SHOP_DIALOG = 7659; --Welcome. Have a look and compare! You'll never find better wares anywhere.
OLWYN_SHOP_DIALOG = 7660; --Welcome to Mjoll's Goods! What can I do for you?
ZAIRA_SHOP_DIALOG = 7661; --Greetings. What spell are you looking for?
SORORO_SHOP_DIALOG = 7662; --Hello-mellow, welcome to Sororo's Scribe and Notary!
HARMODIOS_SHOP_DIALOG = 7663; --Add music to your adventuring life! Welcome to Harmodios's.
CARMELIDE_SHOP_DIALOG = 7664; --Ah, welcome, welcome! What might I interest you in?
RAGHD_SHOP_DIALOG = 7665; --Give a smile to that special someone! Welcome to Carmelide's.
HORTENSE_SHOP_DIALOG = 7666; --Hello there! We have instruments and music sheets at Harmodios's!
OGGODETT_OPEN_DIALOG = 7667; --Hello there! Might I interest you in some specialty goods from Aragoneu?
YAFAFA_OPEN_DIALOG = 7668; --Hello! I've got some goods from Kolshushu--interested?
SOMNPAEMN_OPEN_DIALOG = 7669; --Welcome! I have goods straight from Sarutabaruta! What say you?
-- conquest Base
CONQUEST_BASE = 6567; -- Tallying conquest results...
-- Porter Moogle
RETRIEVE_DIALOG_ID = 12831; -- You retrieve a <item> from the porter moogle's care.
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Port_Jeuno/npcs/Kochahy-Muwachahy.lua | 13 | 3641 | -----------------------------------
-- 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);
if (player:getNation() == 0) then
inventory = SandInv;
size = #SandInv;
elseif (player:getNation() == 1) then
inventory = BastInv;
size = #BastInv;
else
inventory = WindInv;
size = #WindInv;
end
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ?
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
itemCP = inventory[Item + 1];
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
end;
end; | gpl-3.0 |
Armyluix/darkstar | scripts/zones/VeLugannon_Palace/TextIDs.lua | 9 | 1036 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6384; -- Obtained: <item>
GIL_OBTAINED = 6385; -- Obtained <number> gil
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7209; -- You unlock the chest!
CHEST_FAIL = 7210; -- Fails to open the chest.
CHEST_TRAP = 7211; -- The chest was trapped!
CHEST_WEAK = 7212; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7213; -- The chest was a mimic!
CHEST_MOOGLE = 7214; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7215; -- The chest was but an illusion...
CHEST_LOCKED = 7216; -- The chest appears to be locked.
-- Other dialog
NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here.
-- conquest Base
CONQUEST_BASE = 7043; -- Tallying conquest results...
| gpl-3.0 |
abriasffxi/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/npcs/Beastmen_s_Banner.lua | 14 | 1050 | -----------------------------------
-- Area: The_Sanctuary_of_ZiTah
-- NPC: Beastmen_s_Banner
-- @pos -399.822 0.161 -168.998 121
-----------------------------------
package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(BEASTMEN_BANNER);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Lufaise_Meadows/npcs/Teldo-Moroldo_WW.lua | 14 | 3342 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: Teldo-Moroldo, W.W.
-- Outpost Conquest Guards
-- @pos -542.418 -7.124 -53.521 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Lufaise_Meadows/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = TAVNAZIANARCH;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/Telepoint.lua | 17 | 1706 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
item = trade:getItemId();
if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then
if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then
player:tradeComplete();
player:addItem(613);
player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(ALTEPA_GATE_CRYSTAL) == false) then
player:addKeyItem(ALTEPA_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_GATE_CRYSTAL);
else
player:messageSpecial(ALREADY_OBTAINED_TELE);
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 |
jonese1234/PokeBotBad | BizHawk-1.11.6/Lua/SNES/Congo's Caper.lua | 7 | 2866 | -- Congo Caper's Collision Box Viewer
-- Author: Pasky13
camx = 0
camy = 0
memory.usememorydomain("CARTROM")
function findbit(p)
return 2 ^ (p - 1)
end
function hasbit(x, p)
return x % (p + p) >= p
end
local function RetrieveBox(obase, switch)
if switch == 1 then
pointer = mainmemory.read_u8(obase + 0x19)
elseif switch == 2 then
pointer = mainmemory.read_u8(obase + 0x18)
elseif switch == 3 then
pointer = mainmemory.read_u8(obase + 0x1A)
end
local pointer = bit.lshift(pointer,3)
local base = 0x66962
local box = {0, 0, 0, 0 }
box[1] = memory.read_s16_le(base + pointer) -- x1
box[2] = memory.read_s16_le(base + pointer + 4) -- y1
box[3] = memory.read_s16_le(base + pointer + 2) -- x2
box[4] = memory.read_s16_le(base + pointer + 6) -- y2
return box
end
local function camera()
camx = mainmemory.read_u16_le(0x7E0427)
camy = mainmemory.read_u16_le(0x7E0429)
end
local function player()
local x = mainmemory.read_u16_le(0x23) - camx
local y = mainmemory.read_u16_le(0x26) - camy
local face = mainmemory.read_u8(0x2D)
local box
local box = RetrieveBox(0x20,1)
if hasbit(face,findbit(7)) then
gui.drawBox(x - box[1],y + box[2],x - box[3],y + box[4],0xFF0000FF,0x350000FF) -- Hurt box
box = RetrieveBox(0x20,2)
gui.drawBox(x - box[1],y + box[2],x - box[3],y + box[4],0xFFFFFFFF,0x35FFFFFF) -- Hit box
else
gui.drawBox(x + box[1],y + box[2],x + box[3],y + box[4],0xFF0000FF,0x350000FF) -- Hurt box
box = RetrieveBox(0x20,2)
gui.drawBox(x + box[1],y + box[2],x + box[3],y + box[4],0xFFFFFFFF,0x35FFFFFF) -- Hit box
end
end
local function enemies()
local ebase = 0x1100
for i = 0,64,1 do
base = ebase + (i * 0x40)
if mainmemory.read_u8(base) > 0 then
local x = mainmemory.read_u16_le(base + 3) - camx
local y = mainmemory.read_u16_le(base + 6) - camy
local face = mainmemory.read_u8(base + 0xD)
local box = RetrieveBox(base,2)
if hasbit(face,findbit(7)) then
gui.drawBox(x - box[1],y + box[2],x - box[3],y + box[4],0xFFFF0000,0x35FF0000) -- Hit box
box = RetrieveBox(base,1)
gui.drawBox(x - box[1],y + box[2],x - box[3],y + box[4],0xFF0000FF,0x350000FF) -- Hurt box
box = RetrieveBox(base,3)
gui.drawBox(x - box[1],y + box[2],x - box[3],y + box[4],0xFF00FF00,0x3500FF00) -- Can be jumped on box
else
gui.drawBox(x + box[1],y + box[2],x + box[3],y + box[4],0xFFFF0000,0x35FF0000) -- Hit box
box = RetrieveBox(base,1)
gui.drawBox(x + box[1],y + box[2],x + box[3],y + box[4],0xFF0000FF,0x350000FF) -- Hurt box
box = RetrieveBox(base,3)
gui.drawBox(x + box[1],y + box[2],x + box[3],y + box[4],0xFF00FF00,0x3500FF00) -- Can be jumped on box
end
end
end
end
local function scaler()
xm = client.screenwidth() / 256
ym = client.screenheight() / 224
end
while true do
scaler()
camera()
player()
enemies()
emu.frameadvance()
end | mit |
jonese1234/PokeBotBad | BizHawk-1.11.6/Lua/UnitTests/Joypad_RoundTrip.lua | 7 | 3118 | console.clear()
console.writeline("Unit test for joypad.get and joypad.set")
console.writeline("Core Required: NES (or any multi-player core with U,D,L,R,select,start,A,B as buttons)")
console.writeline("")
local test_event
local test_function
local test_frame = 0
function test_1()
-- clear previous input
if test_frame < 4 then
return
end
local test_case = "test_1: set/get round trip"
local test_result = false
-- set expected input
joypad.set({ ["P1 A"] = true, ["P1 B"] = true, ["P1 Select"] = true })
-- get actual input
local t = joypad.get()
-- assert_equal
if t["P1 A"] and t["P1 B"] and t["P1 Select"] then
test_result = true
end
-- finish
console.writeline(string.format("%s (%s): %s", test_case, test_event, test_result and "OK" or "FAILED"))
-- if not test_result then
-- console.writeline("Returned Value:")
-- console.writeline(t)
-- end
return next_test()
end
local test_2_first = true
local test_2_start_pressed = false
function test_2()
if test_frame < 4 then
return
end
local test_case = "test_2: get/set round trip"
if test_2_first then
test_2_first = false
console.writeline(test_case)
console.writeline("Does joypad work normally?")
console.writeline("Press 'P1 Start' if it works good.")
end
if test_frame == 4 then
console.writeline(string.format("%s: running...", test_event))
end
-- round trip (no changes)
local t = joypad.get()
joypad.set(t)
if t["P1 Start"] then
test_2_start_pressed = true
else
if test_2_start_pressed then
test_2_start_pressed = false
next_test()
end
end
end
local test_3_first = true
function test_3()
local test_case = "test_3: test if joypad.get() == movie.getinput(now)?"
if test_3_first then
test_3_first = false
console.writeline(test_case)
end
console.writeline(string.format("%s: test code is not available yet: SKIPPED", test_event))
next_test()
end
local tests = { test_1, test_2, test_3 }
local events = { "event.onframestart", "event.onframeend", "emu.frameadvance" }
local test_event_index = 1
local test_function_index = 1
test_event = events[1]
test_function = tests[1]
function test_reset()
test_frame = 0
end
test_reset()
function next_test()
test_event_index = test_event_index + 1
if test_event_index > #events then
console.writeline("")
test_event_index = 1
test_function_index = test_function_index + 1
if test_function_index > #tests then
console.writeline("Test Finished.")
console.writeline("")
error("Done.")
end
end
test_event = events[test_event_index]
test_function = tests[test_function_index]
test_reset()
end
event.onframestart(function()
if test_event == "event.onframestart" then
test_function()
test_frame = test_frame + 1
end
end)
event.onframeend(function()
if test_event == "event.onframeend" then
test_function()
test_frame = test_frame + 1
end
end)
while true do
if test_event == "emu.frameadvance" then
test_function()
test_frame = test_frame + 1
end
emu.frameadvance()
end
| mit |
abriasffxi/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm10.lua | 14 | 1384 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm10 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos -139.895 -5.500 154.513 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 6) then
player:messageSpecial(PRESENCE_FROM_CEILING);
player:setVar("hittingTheMarquisateHagainCS",7);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
imrandomizer/Algorithm-Implementations | Bresenham_Based_Supercover_Line/Lua/Yonaba/bresenham_based_supercover_test.lua | 27 | 1151 | -- Tests for bresenham.lua
local supercover_line = require 'bresenham_based_supercover'
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
-- Checks if t1 and t2 arrays are the same
local function same(t1, t2)
for k,v in ipairs(t1) do
if t2[k].x ~= v.x or t2[k].y ~= v.y then
return false
end
end
return true
end
run('Testing Bresenham-based supercover line marching', function()
local expected = {
{x = 1, y = 1}, {x = 2, y = 1}, {x = 1, y = 2},
{x = 2, y = 2}, {x = 3, y = 2}, {x = 2, y = 3},
{x = 3, y = 3}, {x = 4, y = 3}, {x = 3, y = 4},
{x = 4, y = 4}, {x = 5, y = 4}, {x = 4, y = 5},
{x = 5, y = 5}
}
assert(same(supercover_line(1, 1, 5, 5), expected))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
abriasffxi/darkstar | scripts/zones/Bastok_Mines/npcs/Proud_Beard.lua | 17 | 1688 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Proud Beard
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
require("scripts/globals/events/harvest_festivals");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
onHalloweenTrade(player,trade,npc)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PROUDBEARD_SHOP_DIALOG);
stock = {
0x3157, 276, --Hume Tunic
0x3158, 276, --Hume Vest
0x31D2, 165, --Hume M Gloves
0x31D8, 165, --Hume F Gloves
0x3253, 239, --Hume Slacks
0x3254, 239, --Hume Pants
0x32CD, 165, --Hume M Boots
0x32D2, 165, --Hume F Boots
0x315D, 276, --Galkan Surcoat
0x31D6, 165, --Galkan Bracers
0x3258, 239, --Galkan Braguette
0x32D1, 165 --Galkan Sandals
}
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
sum2012/mame | 3rdparty/genie/tests/actions/vstudio/cs2005/propertygroup.lua | 47 | 1157 | --
-- tests/actions/vstudio/cs2005/propertygroup.lua
-- Validate configuration <PropertyGroup/> elements in Visual Studio 2005+ .csproj
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
T.vstudio_cs2005_propertygroup = { }
local suite = T.vstudio_cs2005_propertygroup
local cs2005 = premake.vstudio.cs2005
--
-- Setup
--
local sln, prj, cfg
function suite.setup()
sln = test.createsolution()
language "C#"
end
local function prepare()
premake.bake.buildconfigs()
prj = premake.solution.getproject(sln, 1)
cfg = premake.getconfig(prj, "Debug")
cs2005.propertygroup(cfg)
end
--
-- Version Tests
--
function suite.OnVs2005()
_ACTION = "vs2005"
prepare()
test.capture [[
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
]]
end
function suite.OnVs2008()
_ACTION = "vs2008"
prepare()
test.capture [[
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
]]
end
function suite.OnVs2010()
_ACTION = "vs2010"
prepare()
test.capture [[
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
]]
end
| gpl-2.0 |
dvv/luvit-cjson | test.lua | 1 | 1321 | #!/usr/bin/env luvit
local JSON = require('./')
assert(not _G.json)
assert(JSON.stringify)
assert(JSON.parse)
assert(JSON.null)
local obj, serialized, content
obj = { 1, 2, 3, 4 }
p(obj)
serialized = JSON.stringify(obj)
p(serialized)
content = JSON.parse(serialized)
p(content)
assert(obj[2] == content[2])
obj = { a = {'foo', true, false} }
p(obj)
serialized = JSON.stringify(obj)
p(serialized)
content = JSON.parse(serialized)
p(content)
assert(obj.a[3] == content.a[3])
-- multivalue
p(JSON.parse('[1][2]\n[3]\n', { allow_multiple_values = true }))
p(#JSON.parse(('[1]\n'):rep(40000), { allow_multiple_values = true }))
do
local results = {}
local parser = JSON.streamingParser(function(value)
results[#results + 1] = value
if #results == 30 then
print('OK')
end
end, { allow_multiple_values = true })
local status, result = pcall(parser.parse, parser, ('[2]\n'):rep(30))
p(status, result, #results)
--assert(status)
--assert(#result == 10000)
end
-- streaming
do
local results = {}
local parser = JSON.streamingParser(function(value)
p('VALUE:', value)
end, { allow_multiple_values = true })
parser:parse('[1')
parser:parse(']\n[2]\n[')
end
--[[
-- bad unicode
local lookup = require('fs').readFileSync('tests/lookup.txt')
lookup = JSON.parse(lookup)
p(lookup)
]]
| mit |
dios-game/dios-cocos | src/oslibs/cocos/cocos-src/cocos/scripting/lua-bindings/auto/api/EaseQuinticActionOut.lua | 9 | 1432 |
--------------------------------
-- @module EaseQuinticActionOut
-- @extend ActionEase
-- @parent_module cc
--------------------------------
-- brief Create the action with the inner action.<br>
-- param action The pointer of the inner action.<br>
-- return A pointer of EaseQuinticActionOut action. If creation failed, return nil.
-- @function [parent=#EaseQuinticActionOut] create
-- @param self
-- @param #cc.ActionInterval action
-- @return EaseQuinticActionOut#EaseQuinticActionOut ret (return value: cc.EaseQuinticActionOut)
--------------------------------
--
-- @function [parent=#EaseQuinticActionOut] clone
-- @param self
-- @return EaseQuinticActionOut#EaseQuinticActionOut ret (return value: cc.EaseQuinticActionOut)
--------------------------------
--
-- @function [parent=#EaseQuinticActionOut] update
-- @param self
-- @param #float time
-- @return EaseQuinticActionOut#EaseQuinticActionOut self (return value: cc.EaseQuinticActionOut)
--------------------------------
--
-- @function [parent=#EaseQuinticActionOut] reverse
-- @param self
-- @return EaseQuinticActionOut#EaseQuinticActionOut ret (return value: cc.EaseQuinticActionOut)
--------------------------------
--
-- @function [parent=#EaseQuinticActionOut] EaseQuinticActionOut
-- @param self
-- @return EaseQuinticActionOut#EaseQuinticActionOut self (return value: cc.EaseQuinticActionOut)
return nil
| mit |
JKGDevs/JediKnightGalaxies | JKGalaxies/glua/maps/jkg_arena_tatooine_night/events.lua | 3 | 4447 | --[[ ------------------------------------------------
Jedi Knight Galaxies Lua Code
Tatooine arena backend: events
Written by BobaFett
--------------------------------------------------]]
local backend = JKG.ArenaBackend
local controls = backend.Controls
local evt = backend.Events -- For higher speed and quicker access
local MS_NONE = 0 -- No matches in progress
local MS_AWAITINGPLAYERS = 1 -- Players are being summoned to the waiting rooms
local MS_STARTING = 2 -- Players are in the waiting rooms, doing 10 sec countdown
local MS_INPROGRESS = 3 -- The match is in progress
local MS_FINISHED = 4 -- The match finished, people can now leave the arena
-- Match Game Modes
local MGM_NONE = 0
local MGM_REINFORCEMENTS = 1
local MGM_KILLS = 2
local MGM_MAX = 3
function evt.OnPlayerDeath(ply, inflictor, attacker, damage, means)
-- Player died, check if he's on one of the teams
local arena,team = backend.FindPlayer(ply)
if arena == 0 then
return
elseif arena == 1 then
local data = backend.Data
if data.MainArena.Stage ~= MS_INPROGRESS then return end
if data.MainArena.GameMode == MGM_REINFORCEMENTS then
if team == 1 then
data.MainArena.RedScore = data.MainArena.RedScore - 1
controls.SetRedReinforcements(data.MainArena.RedScore >= 0 and data.MainArena.RedScore or 0)
if data.MainArena.RedScore <= -#data.MainArena.RedTeam then
-- Game finished
backend.GameFinished(1, 1)
end
elseif team == 2 then
data.MainArena.BlueScore = data.MainArena.BlueScore - 1
controls.SetBlueReinforcements(data.MainArena.BlueScore >= 0 and data.MainArena.BlueScore or 0)
if data.MainArena.BlueScore <= -#data.MainArena.BlueTeam then
-- Game finished
backend.GameFinished(1, 1)
end
end
elseif data.MainArena.GameMode == MGM_KILLS then
if team == 1 then
data.MainArena.BlueScore = data.MainArena.BlueScore + 1
controls.SetBlueScore(data.MainArena.BlueScore)
if data.MainArena.BlueScore >= data.MainArena.KillLimit then
-- Game finished
backend.GameFinished(1, 1)
end
elseif team == 2 then
data.MainArena.RedScore = data.MainArena.RedScore + 1
controls.SetRedScore(data.MainArena.RedScore)
if data.MainArena.RedScore >= data.MainArena.KillLimit then
-- Game finished
backend.GameFinished(1, 1)
end
end
end
elseif arena == 2 then
end
end
hook.Add("PlayerDeath", "ArenaPlayerDeath", evt.OnPlayerDeath)
function evt.OnPlayerDeathcam(ply)
-- Player died, check if he's on one of the teams
local arena,team = backend.FindPlayer(ply)
if arena == 0 then
return
elseif arena == 1 then
local data = backend.Data
if data.MainArena.Stage < MS_INPROGRESS then return end
if data.MainArena.GameMode == MGM_REINFORCEMENTS then
if data.MainArena.Stage == MS_FINISHED then return -1 end
if team == 1 then
if data.MainArena.RedScore < 0 then
return (data.MainArena.TimeLeft + 60) * 1000
else
return -1
end
elseif team == 2 then
if data.MainArena.BlueScore < 0 then
return (data.MainArena.TimeLeft + 60) * 1000
else
return -1
end
end
elseif data.MainArena.GameMode == MGM_KILLS then
return -1
end
elseif arena == 2 then
end
end
hook.Add("PlayerDeathcam", "ArenaPlayerDeathcam", evt.OnPlayerDeathcam, 10)
function evt.OnSelectSpawn(ply, team, avoidpoint)
-- Player died, check if he's on one of the teams
local arena,pteam = backend.FindPlayer(ply)
if arena == 0 then
return
elseif arena == 1 then
local data = backend.Data
local spawnlist
if pteam == 1 then
spawnlist = ents.GetByName("3v3InArenaRed")
elseif pteam == 2 then
spawnlist = ents.GetByName("3v3InArenaBlue")
else
return
end
while 1 do
local n = math.random(1, #spawnlist)
if not sys.SpotWouldTelefrag(ply.Entity, spawnlist[n]:GetPos()) then
return spawnlist[n]
end
if #spawnlist == 1 then
return spawnlist[1]
end
table.remove(spawnlist, n)
end
elseif arena == 2 then
end
end
hook.Add("SelectSpawn", "ArenaSelectSpawn", evt.OnSelectSpawn, 10)
function evt.OnPlayerSpawned(ply)
-- Player died, check if he's on one of the teams
local arena,pteam = backend.FindPlayer(ply)
if arena == 0 then
return
elseif arena == 1 then
ply.NoDismember = true
ply.NoDisintegrate = true
backend.DoLoadout(1, ply)
elseif arena == 2 then
end
end
hook.Add("PlayerSpawned", "ArenaPlayerSpawned", evt.OnPlayerSpawned, 10)
| gpl-2.0 |
girvo/textadept-config | modules/textredux/fs.lua | 1 | 16237 | --[[--
textredux.fs provides file system related functions and a text based file
browser for Textadept.
It features traditional directory browsing, snapopen functionality, completely
keyboard driven interaction, and provides powerful narrow to search
functionality.
Some tips on using the file browser
-----------------------------------
*Switching between traditional browsing and snapopen*
As said above the file browser allows both traditional browsing as well as
snapopen functionality. But it also allows you to seamlessly switch between
the two modes (by default, `Ctrl + s` is assigned for this).
*Quickly moving up one directory level*
In traditional browsing mode, you can always select `..` to move up one
directory level. But a quicker way of doing the same is to press `<backspace>`
when you have an empty search. This also works when in snapopen mode.
*Opening a sub directory in snapopen mode*
In contrast with Textadept snapopen, you will in snapopen mode also see sub
directories in the listing. This is by design - you can select a sub directory
to snapopen that directory.
*Changing the styles used for different file types*
If you don't like the default styles (colors, etc.) used by the file browser,
you can easily change these by customizing any of the `style_<foo>` entries
using the Textredux style module. As an example, to make directory entries
underlined you would do something like the following:
textredux.core.style.fs_directory = { underline = true }
Please see the documentation for the Textredux style module for instructions
on how to define styles.
@author Nils Nordman <nino at nordman.org>
@copyright 2011-2012
@license MIT (see LICENSE)
@module textredux.fs
]]
local tr_list = require 'textredux.core.list'
local tr_style = require 'textredux.core.style'
local tr_ui = require 'textredux.core.ui'
local _G, table, io, ui = _G, table, io, ui
local ipairs, error, type, assert, pcall =
ipairs, error, type, assert, pcall
local string_match, string_sub = string.match, string.sub
local lfs = require 'lfs'
local WIN32 = WIN32
local user_home = os.getenv('HOME') or os.getenv('UserProfile')
local fs_attributes = WIN32 and lfs.attributes or lfs.symlinkattributes
local separator = WIN32 and '\\' or '/'
local updir_pattern = '%.%.?$'
local M = {}
local _ENV = M
if setfenv then setfenv(1, _ENV) end
--- The style used for directory entries.
tr_style.fs_directory = tr_style.keyword
--- The style used for ordinary file entries.
tr_style.fs_file = tr_style.string
--- The style used for link entries.
tr_style.fs_link = tr_style.operator
--- The style used for socket entries.
tr_style.fs_socket = tr_style.error
--- The style used for pipe entries.
tr_style.fs_pipe = tr_style.error
--- The style used for pipe entries.
tr_style.fs_device = tr_style.error
local file_styles = {
directory = tr_style.fs_directory,
file = tr_style.fs_file,
link = tr_style.fs_link,
socket = tr_style.fs_socket,
['named pipe'] = tr_style.fs_pipe,
['char device'] = tr_style.fs_device,
['block device'] = tr_style.fs_device,
other = tr_style.default
}
local DEFAULT_DEPTH = 99
-- Splits a path into its components
function split_path(path)
local parts = {}
for part in path:gmatch('[^' .. separator .. ']+') do
parts[#parts + 1] = part
end
return parts
end
-- Joins path components into a path
function join_path(components)
local start = WIN32 and '' or separator
return start .. table.concat(components, separator)
end
-- Returns the dir part of path
function dirname(path)
local parts = split_path(path)
table.remove(parts)
local dir = join_path(parts)
if #dir == 0 then return path end -- win32 root
return dir
end
function basename(path)
local parts = split_path(path)
return parts[#parts]
end
-- Normalizes the path. This will deconstruct and reconstruct the
-- path's components, while removing any relative parent references
function normalize_path(path)
local parts = split_path(path)
local normalized = {}
for _, part in ipairs(parts) do
if part == '..' then
table.remove(normalized)
else
normalized[#normalized + 1] = part
end
end
if #normalized == 1 and WIN32 then -- TODO: win hack
normalized[#normalized + 1] = ''
end
return join_path(normalized)
end
-- Normalizes a path denoting a directory. This will do the same as
-- normalize_path, but will in addition ensure that the path ends
-- with a trailing separator
function normalize_dir_path(directory)
local path = normalize_path(directory)
return string_sub(path, -1) == separator and path or path .. separator
end
local function parse_filters(filter)
local filters = {}
for _, restriction in ipairs(filter) do
if type(restriction) == 'string' then
local negated = restriction:match('^!(.+)')
local filter_pattern = negated or restriction
restriction = function(path)
if path:match(filter_pattern) then
if not negated then return true end
elseif negated then return true
else return false end
end
end
filters[#filters + 1] = restriction
end
return filters
end
local function add_extensions_filter(filters, extensions)
if extensions and #extensions > 0 then
local exts = {}
for _, ext in ipairs(extensions) do exts[ext] = true end
filters[#filters + 1] = function(path)
return exts[string_match(path, '%.(%a+)$')] ~= nil
end
end
end
-- Given the patterns, returns a function returning true if
-- the path should be filtered, and false otherwise
local function create_filter(filter)
local filters = parse_filters(filter)
add_extensions_filter(filters, filter.extensions)
filters.directory = parse_filters(filter.folders or {})
return function(file)
local filters = filters[file.mode] or filters
for _, filter in ipairs(filters) do
if filter(file.path) then return true end
end
return false
end
end
local function file(path, name, parent)
local file, error = fs_attributes(path)
if error then file = { mode = 'error' } end
local suffix = file.mode == 'directory' and separator or ''
file.path = path
file.hidden = name and string_sub(name, 1, 1) == '.'
if parent then
file.rel_path = parent.rel_path .. name .. suffix
file.depth = parent.depth + 1
else
file.rel_path = ''
file.depth = 1
end
file[1] = file.rel_path
return file
end
local function find_files(directory, filter, depth, max_files)
if not directory then error('Missing argument #1 (directory)', 2) end
if not depth then error('Missing argument #3 (depth)', 2) end
if type(filter) ~= 'function' then filter = create_filter(filter) end
local files = {}
directory = normalize_path(directory)
local directories = { file(directory) }
while #directories > 0 do
local dir = table.remove(directories)
if dir.depth > 1 then files[#files + 1] = dir end
if dir.depth <= depth then
local status, entries, dir_obj = pcall(lfs.dir, dir.path)
if status then
for entry in entries, dir_obj do
local file = file(dir.path .. separator .. entry, entry, dir)
if not filter(file) then
if file.mode == 'directory' and entry ~= '..' and entry ~= '.' then
table.insert(directories, 1, file)
else
if max_files and #files == max_files then return files, false end
files[#files + 1] = file
end
end
end
end
end
end
return files, true
end
local function sort_items(items)
table.sort(items, function (a, b)
local parent_path = '..' .. separator
if a.rel_path == parent_path then return true
elseif b.rel_path == parent_path then return false
elseif a.hidden ~= b.hidden then return b.hidden
elseif a.mode == 'directory' and b.mode ~= 'directory' then return true
elseif b.mode == 'directory' and a.mode ~= 'directory' then return false
end
return (a.rel_path < b.rel_path)
end)
end
local function chdir(list, directory)
directory = normalize_path(directory)
local data = list.data
local items, complete = find_files(directory, data.filter, data.depth, data.max_files)
if data.depth == 1 then sort_items(items) end
list.title = directory
list.items = items
data.directory = directory
list:show()
if #items > 1 and items[1].rel_path:match('^%.%..?$') then
list.buffer:line_down()
end
if not complete then
local status = 'Number of entries limited to ' ..
data.max_files .. ' as per io.SNAPOPEN_MAX'
ui.statusbar_text = status
else
ui.statusbar_text = ''
end
end
local function open_selected_file(path, exists, list, shift, ctrl)
if not exists then
local file, error = io.open(path, 'wb')
if not file then
ui.statusbar_text = 'Could not create ' .. path .. ': ' .. error
return
end
file:close()
end
list:close()
if ctrl then tr_ui.switch_to_other_view() end
io.open_file(path)
end
function on_keypress(list, key, code, shift, ctl, alt, meta)
if ctl or alt or meta or not key then return end
if key == '\b' and not list:get_current_search() then
local parent = dirname(list.data.directory)
if parent ~= list.data.directory then
chdir(list, parent)
return true
end
end
end
local function get_initial_directory()
local filename = _G.buffer.filename
if filename then return dirname(filename) end
return user_home
end
local function get_file_style(item, index)
return file_styles[item.mode] or tr_style.default
end
local function toggle_snap(list)
local data = list.data
local depth = data.depth
if data.prev_depth then
data.depth = data.prev_depth
else
data.depth = data.depth == 1 and DEFAULT_DEPTH or 1
end
local filter = data.filter
if data.depth == 1 then -- remove updir filter
if type(filter.folders) == 'table' then
for i, restriction in ipairs(filter.folders) do
if restriction == updir_pattern then
table.remove(filter.folders, i)
break
end
end
end
else -- add updir filter
filter.folders = filter.folders or {}
filter.folders[#filter.folders + 1] = updir_pattern
end
data.prev_depth = depth
chdir(list, data.directory)
end
local function create_list(directory, filter, depth, max_files)
local list = tr_list.new(directory)
local data = list.data
list.on_keypress = on_keypress
list.column_styles[1] = get_file_style
list.keys.esc = function() list:close() end
list.keys.cs = toggle_snap
list.keys['~'] = function()
if user_home then chdir(list, user_home) end
end
data.directory = directory
data.filter = filter
data.depth = depth
data.max_files = max_files
return list
end
--[[- Opens a file browser and lets the user choose a file.
@param on_selection The function to invoke when the user has choosen a file.
The function will be called with following parameters:
- `path`: The full path of the choosen file (UTF-8 encoded).
- `exists`: A boolean indicating whether the file exists or not.
- `list`: A reference to the Textredux list used by browser.
- `shift`: True if the Shift key was held down.
- `ctrl`: True if the Control key was held down.
- `alt`: True if the Alt/Option key was held down.
- `meta`: True if the Command/Meta key on Mac OS X/Curses was held down.
The list will not be closed automatically, so close it explicitly using
`list:close()` if desired.
@param start_directory The initial directory to open, in UTF-8 encoding. If
nil, the initial directory is determined automatically (preferred choice is to
open the directory containing the current file).
@param filter The filter to apply, if any. The structure and semantics are the
same as for Textadept's
[snapopen](http://foicica.com/textadept/api/io.html#snapopen).
@param depth The number of directory levels to display in the list. Defaults to
1 if not specified, which results in a "normal" directory listing.
@param max_files The maximum number of files to scan and display in the list.
Defaults to 10000 if not specified.
]]
function select_file(on_selection, start_directory, filter, depth, max_files)
start_directory = start_directory or get_initial_directory()
if not filter then filter = {}
elseif type(filter) == 'string' then filter = { filter } end
filter.folders = filter.folders or {}
filter.folders[#filter.folders + 1] = separator .. '%.$'
local list = create_list(start_directory, filter, depth or 1,
max_files or 10000)
list.on_selection = function(list, item, shift, ctrl, alt, meta)
local path, mode = item.path, item.mode
if mode == 'link' then
mode = lfs.attributes(path, 'mode')
end
if mode == 'directory' then
chdir(list, path)
else
on_selection(path, true, list, shift, ctrl, alt, meta)
end
end
list.on_new_selection = function(list, name, shift, ctrl, alt, meta)
local path = split_path(list.data.directory)
path[#path + 1] = name
on_selection(join_path(path), false, list, shift, ctrl, alt, meta)
end
chdir(list, start_directory)
end
--- Opens the specified directory for browsing.
-- @param start_directory The directory to open, in UTF-8 encoding
function open_file(start_directory)
local filter = { folders = { separator .. '%.$' } }
select_file(open_selected_file, start_directory, filter, 1, io.SNAPOPEN_MAX)
end
--- Saves the current buffer under a new name.
-- Open a browser and lets the user select a name.
function save_buffer_as()
local buffer = _G.buffer
local confirm_path
local function set_file_name(path, exists, list)
if not exists or path == confirm_path then
list:close()
_G.view:goto_buffer(_G._BUFFERS[buffer], false)
io.save_file_as(path)
ui.statusbar_text = ''
else
ui.statusbar_text = 'File exists (' .. path ..
'): Press enter to overwrite.'
confirm_path = path
end
end
local filter = { folders = { separator .. '%.$' } }
select_file(set_file_name, nil, filter, 1)
ui.statusbar_text = 'Save file: select file name to save as..'
end
--- Saves the current buffer.
-- Prompts the users for a filename if it's a new, previously unsaved buffer.
function save_buffer()
local buffer = _G.buffer
if buffer.filename then
io.save()
else
save_buffer_as()
end
end
--[[-
Opens a list of files in the specified directory, according to the given
parameters. This works similarily to
[Textadept snapopen](http://foicica.com/textadept/api/io.html#snapopen).
The main differences are:
- it does not support opening multiple paths at once
- filter can contain functions as well as patterns (and can be a function as well).
Functions will be passed a file object which is the same as the return from
[lfs.attributes](http://keplerproject.github.com/luafilesystem/manual.html#attributes),
with the following additions:
- `rel_path`: The path of the file relative to the currently
displayed directory.
- `hidden`: Whether the path denotes a hidden file.
@param directory The directory to open, in UTF-8 encoding.
@param filter The filter to apply. The format and semantics are the same as for
Textadept.
@param exclude_FILTER Same as for Textadept: unless if not true then
snapopen.FILTER will be automatically added to the filter.
to snapopen.FILTER if not specified.
@param depth The number of directory levels to scan. Defaults to DEFAULT_DEPTH
if not specified.
]]
function snapopen(directory, filter, exclude_FILTER, depth)
if not directory then error('directory not specified', 2) end
if not depth then depth = DEFAULT_DEPTH end
filter = filter or {}
if type(filter) == 'string' then filter = { filter } end
filter.folders = filter.folders or {}
filter.folders[#filter.folders + 1] = updir_pattern
if not exclude_FILTER then
for _, key in ipairs({ 'folders', 'extensions' }) do
filter[key] = filter[key] or {}
for _, pattern in ipairs(lfs.FILTER[key]) do
filter[key][#filter[key] + 1] = pattern
end
end
end
select_file(open_selected_file, directory, filter, depth, io.SNAPOPEN_MAX)
end
return M
| mit |
abriasffxi/darkstar | scripts/zones/Sealions_Den/mobs/Mammet-22_Zeta.lua | 23 | 4284 | -----------------------------------
-- Area: Sealions Den
-- Mob: Mammet-22_Zeta
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local MammetID = mob:getID();
-- printf("MammetID dead: %u",MammetID);
local mammet_1_1 = GetMobAction(16908289);
local mammet_1_2 = GetMobAction(16908290);
local mammet_1_3 = GetMobAction(16908291);
local mammet_1_4 = GetMobAction(16908292);
local mammet_1_5 = GetMobAction(16908293);
local mammet_2_1 = GetMobAction(16908296);
local mammet_2_2 = GetMobAction(16908297);
local mammet_2_3 = GetMobAction(16908298);
local mammet_2_4 = GetMobAction(16908299);
local mammet_2_5 = GetMobAction(16908300);
local mammet_3_1 = GetMobAction(16908303);
local mammet_3_2 = GetMobAction(16908304);
local mammet_3_3 = GetMobAction(16908305);
local mammet_3_4 = GetMobAction(16908306);
local mammet_3_5 = GetMobAction(16908307);
if (MammetID == 16908289 or MammetID == 16908290 or MammetID == 16908291 or MammetID == 16908292 or MammetID == 16908293) then
if ((mammet_1_1 == 0 or mammet_1_1 == 21 or mammet_1_1 == 22 or mammet_1_1 == 23)and
(mammet_1_2 == 0 or mammet_1_2 == 21 or mammet_1_2 == 22 or mammet_1_2 == 23)and
(mammet_1_3 == 0 or mammet_1_3 == 21 or mammet_1_3 == 22 or mammet_1_3 == 23)and
(mammet_1_4 == 0 or mammet_1_4 == 21 or mammet_1_4 == 22 or mammet_1_4 == 23)and
(mammet_1_5 == 0 or mammet_1_5 == 21 or mammet_1_5 == 22 or mammet_1_5 == 23)) then
player:startEvent(0x000b);
end
elseif (MammetID == 16908297 or MammetID == 16908298 or MammetID == 16908299 or MammetID == 16908300 or MammetID == 16908296) then
if ((mammet_2_1 == 0 or mammet_2_1 == 21 or mammet_2_1 == 22 or mammet_2_1 == 23)and
(mammet_2_2 == 0 or mammet_2_2 == 21 or mammet_2_2 == 22 or mammet_2_2 == 23)and
(mammet_2_3 == 0 or mammet_2_3 == 21 or mammet_2_3 == 22 or mammet_2_3 == 23)and
(mammet_2_4 == 0 or mammet_2_4 == 21 or mammet_2_4 == 22 or mammet_2_4 == 23)and
(mammet_2_5 == 0 or mammet_2_5 == 21 or mammet_2_5 == 22 or mammet_2_5 == 23)) then
player:startEvent(0x000b);
end
elseif (MammetID == 16908303 or MammetID == 16908304 or MammetID == 16908305 or MammetID == 16908306 or MammetID == 16908307) then
if ((mammet_3_1 == 0 or mammet_3_1 == 21 or mammet_3_1 == 22 or mammet_3_1 == 23)and
(mammet_3_2 == 0 or mammet_3_2 == 21 or mammet_3_2 == 22 or mammet_3_2 == 23)and
(mammet_3_3 == 0 or mammet_3_3 == 21 or mammet_3_3 == 22 or mammet_3_3 == 23)and
(mammet_3_4 == 0 or mammet_3_4 == 21 or mammet_3_4 == 22 or mammet_3_4 == 23)and
(mammet_3_5 == 0 or mammet_3_5 == 21 or mammet_3_5 == 22 or mammet_3_5 == 23)) then
player:startEvent(0x000b);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x000b) then
local instance = player:getVar("bcnm_instanceid")
--Players are healed in between the fights, but their TP is set to 0
player:setHP(player:getMaxHP());
player:setMP(player:getMaxMP());
player:setTP(0);
if (instance == 1) then
player:setPos(-779, -103, -80);
SpawnMob(16908294); -- omega1
elseif (instance == 2) then
player:setPos(-140, -23, -440);
SpawnMob(16908301); -- omega2
else
player:setPos(499, 56, -802);
SpawnMob(16908308); -- omega 3
end
player:addTitle(BRANDED_BY_LIGHTNING);
end
end; | gpl-3.0 |
abriasffxi/darkstar | scripts/zones/Zeruhn_Mines/npcs/Zelman.lua | 17 | 1793 | -----------------------------------
-- Area: Zeruhn Mines
-- NPC: Zelman
-- Involved In Quest: Groceries
-----------------------------------
package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Zeruhn_Mines/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local GroceriesVar = player:getVar("Groceries");
local GroceriesViewedNote = player:getVar("GroceriesViewedNote");
if (GroceriesVar == 2) then
player:showText(npc,7279);
elseif (GroceriesVar == 1) then
ViewedNote = player:seenKeyItem(TAMIS_NOTE);
if (ViewedNote == true) then
player:startEvent(0x00a2);
else
player:startEvent(0x00a1);
end
else
player:startEvent(0x00a0);
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 == 0x00a1) then
player:setVar("Groceries",2);
player:delKeyItem(TAMIS_NOTE);
elseif (csid == 0x00a2) then
player:setVar("GroceriesViewedNote",1);
player:delKeyItem(TAMIS_NOTE);
end
end;
| gpl-3.0 |
abriasffxi/darkstar | scripts/globals/items/lungfish.lua | 18 | 1304 | -----------------------------------------
-- ID: 4315
-- Item: Lungfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -2
-- Mind 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
elseif (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4315);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -2);
target:addMod(MOD_MND, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -2);
target:delMod(MOD_MND, 4);
end;
| gpl-3.0 |
ElectroDuk/QuackWars | garrysmod/gamemodes/Basewars/entities(maybe_outdated)/effects/super_explosion2/uncloak/init.lua | 5 | 1076 | -- simple unloack effect :/
--Initializes the effect. The data is a table of data
--which was passed from the server.
function EFFECT:Init( data )
self.Position = data:GetOrigin()
local Pos = self.Position
local Norm = Vector(0,0,1)
Pos = Pos + Norm * 6
local emitter = ParticleEmitter( Pos )
for i=1,math.random(15,25) do
local particle = emitter:Add( "particles/smokey", Pos + Vector(0,0,math.random(0,100)))
particle:SetVelocity(Vector(math.random(-30,30),math.random(-30,30), math.random(-5, 50)))
particle:SetDieTime(math.Rand( 2.5, 5 ))
particle:SetStartAlpha(150)
particle:SetStartSize( math.random(15, 40) )
particle:SetEndSize( math.random(40, 55) )
particle:SetRoll( math.Rand( 360, 480 ) )
particle:SetRollDelta( math.Rand( -1, 1 ) )
particle:SetColor( 255, 255, 255 )
particle:VelocityDecay( false )
end
emitter:Finish()
end
function EFFECT:Think( )
return true
end
-- Draw the effect
function EFFECT:Render()
-- Do nothing - this effect is only used to spawn the particles in Init
end
| mit |
abriasffxi/darkstar | scripts/zones/Jugner_Forest_[S]/npcs/Gate_Sentry.lua | 14 | 1042 | -----------------------------------
-- Area: Jugner Forest (S)
-- NPC: Gate Sentry
-- Type: Standard NPC
-- @pos -265.235 -2.399 405.246 82
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Jugner_Forest_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00fd);
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 |
Armyluix/darkstar | scripts/globals/abilities/building_flourish.lua | 28 | 2817 | -----------------------------------
-- Ability: Building Flourish
-- Enhances potency of your next weapon skill. Requires at least one Finishing Move.
-- Obtained: Dancer Level 50
-- Finishing Moves Used: 1-3
-- Recast Time: 00:10
-- Duration: 01:00
--
-- Using one Finishing Move boosts the Accuracy of your next weapon skill.
-- Using two Finishing Moves boosts both the Accuracy and Attack of your next weapon skill.
-- Using three Finishing Moves boosts the Accuracy, Attack and Critical Hit Rate of your next weapon skill.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
return 0,0;
else
return MSGBASIC_NO_FINISHINGMOVES,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,1,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,2,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_3);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_5);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
end;
end; | gpl-3.0 |
Armyluix/darkstar | scripts/globals/abilities/pets/somnolence.lua | 12 | 1384 | ---------------------------------------------------
-- Somnolence
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local spell = getSpell(165); --gave the ability the same power as Thunder II
local dmg = calculateMagicDamage(178,1,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
local dINT = pet:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyPlayerResistance(pet,-1,target, dINT, ELEMENTAL_MAGIC_SKILL, ELE_DARK);
local tp = skill:getTP();
local duration = 120;
dmg = dmg*resist;
dmg = mobAddBonuses(pet,spell,target,dmg, ELE_DARK);
if (tp < 100) then
tp = 100;
end
dmg = dmg * tp / 100;
dmg = finalMagicAdjustments(pet,target,spell,dmg);
if (resist < 0.15) then --the gravity effect from this ability is more likely to land than Tail Whip
resist = 0;
end
duration = duration * resist;
if (duration > 0 and target:hasStatusEffect(EFFECT_WEIGHT) == false) then
target:addStatusEffect(EFFECT_WEIGHT, 50, 0, duration);
end
return dmg;
end | gpl-3.0 |
urueedi/luci | applications/luci-app-upnp/luasrc/controller/upnp.lua | 20 | 1886 | -- 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.
module("luci.controller.upnp", package.seeall)
function index()
if not nixio.fs.access("/etc/config/upnpd") then
return
end
local page
page = entry({"admin", "services", "upnp"}, cbi("upnp/upnp"), _("UPnP"))
page.dependent = true
entry({"admin", "services", "upnp", "status"}, call("act_status")).leaf = true
entry({"admin", "services", "upnp", "delete"}, post("act_delete")).leaf = true
end
function act_status()
local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD 2>/dev/null")
if ipt then
local fwd = { }
while true do
local ln = ipt:read("*l")
if not ln then
break
elseif ln:match("^%d+") then
local num, proto, extport, intaddr, intport =
ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)")
if num and proto and extport and intaddr and intport then
num = tonumber(num)
extport = tonumber(extport)
intport = tonumber(intport)
fwd[#fwd+1] = {
num = num,
proto = proto:upper(),
extport = extport,
intaddr = intaddr,
intport = intport
}
end
end
end
ipt:close()
luci.http.prepare_content("application/json")
luci.http.write_json(fwd)
end
end
function act_delete(num)
local idx = tonumber(num)
local uci = luci.model.uci.cursor()
if idx and idx > 0 then
luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx)
luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx)
local lease_file = uci:get("upnpd", "config", "upnp_lease_file")
if lease_file and nixio.fs.access(lease_file) then
luci.sys.call("sed -i -e '%dd' %q" %{ idx, lease_file })
end
luci.http.status(200, "OK")
return
end
luci.http.status(400, "Bad request")
end
| apache-2.0 |
Whit3Tig3R/ZeDspammbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.