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 |
|---|---|---|---|---|---|
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/mactodevinfo.lua | 12 | 1309 | --[[
LuCI - Lua Configuration Interface
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: mactodevinfo.lua 5448 2009-10-31 15:54:11Z jow $
]]--
m = Map("mactodevinfo", luci.i18n.translate("MAC Device Info Overrides"), translate("Override the information returned by the MAC to Device Info Script (mac-to-devinfo) for a specified range of MAC Addresses"))
s = m:section(TypedSection, "mactodevinfo", translate("MAC Device Override"), translate("MAC range and information used to override system and IEEE databases"))
s.addremove = true
s.anonymous = true
v = s:option(Value, "name", translate("Name"))
v.optional = true
v = s:option(Value, "maclow", translate("Beginning of MAC address range"))
v.optional = false
v = s:option(Value, "machigh", translate("End of MAC address range"))
v.optional = false
v = s:option(Value, "vendor", translate("Vendor"))
v.optional = false
v = s:option(Value, "devtype", translate("Device Type"))
v.optional = false
v = s:option(Value, "model", translate("Model"))
v.optional = false
v = s:option(Value, "ouiowneroverride", translate("OUI Owner"))
v.optional = true
return m
| gpl-2.0 |
jshackley/darkstar | scripts/globals/abilities/altruism.lua | 28 | 1176 | -----------------------------------
-- Ability: Altruism
-- Increases the accuracy of your next White Magic spell.
-- Obtained: Scholar Level 75 Tier 2 Merit Points
-- Recast Time: Stratagem Charge
-- Duration: 1 white magic spell or 60 seconds, whichever occurs first
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_ALTRUISM) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:addStatusEffect(EFFECT_ALTRUISM,player:getMerit(MERIT_ALTRUISM),0,60);
return EFFECT_ALTRUISM;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Wajaom_Woodlands/npcs/qm3.lua | 30 | 1356 | -----------------------------------
-- Area: Wajaom Woodlands
-- NPC: ??? (Spawn Gotoh Zha the Redolent(ZNM T3))
-- @pos -337 -31 676 51
-----------------------------------
package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Wajaom_Woodlands/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 16986430;
if (trade:hasItemQty(2575,1) and trade:getItemCount() == 1) then -- Trade Sheep Botfly
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
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 |
jshackley/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Pogigi.lua | 38 | 1050 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Pogigi
-- Type: Sealed Container
-- @zone: 94
-- @pos -29.787 -4.499 42.603
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x014a);
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 |
birkett/MCServer | Server/Plugins/APIDump/Hooks/OnExecuteCommand.lua | 36 | 2087 | return
{
HOOK_EXECUTE_COMMAND =
{
CalledWhen = [[
A player executes an in-game command, or the admin issues a console command. Note that built-in
console commands are exempt to this hook - they are always performed and the hook is not called.
]],
DefaultFnName = "OnExecuteCommand", -- also used as pagename
Desc = [[
A plugin may implement a callback for this hook to intercept both in-game commands executed by the
players and console commands executed by the server admin. The function is called for every in-game
command sent from any player and for those server console commands that are not built in in the
server.</p>
<p>
If the command is in-game, the first parameter to the hook function is the {{cPlayer|player}} who's
executing the command. If the command comes from the server console, the first parameter is nil.</p>
<p>
The server calls this hook even for unregistered (unknown) console commands. It also calls the hook
for unknown in-game commands, as long as they begin with a slash ('/'). If a plugin needs to intercept
in-game chat messages not beginning with a slash, it should use the {{OnChat|HOOK_CHAT}} hook.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "For in-game commands, the player who has sent the message. For console commands, nil" },
{ Name = "CommandSplit", Type = "array-table of strings", Notes = "The command and its parameters, broken into a table by spaces" },
{ Name = "EntireCommand", Type = "string", Notes = "The entire command as a single string" },
},
Returns = [[
If the plugin returns false, Cuberite calls all the remaining hook handlers and finally the command
will be executed. If the plugin returns true, the none of the remaining hook handlers will be called.
In this case the plugin can return a second value, specifying whether what the command result should
be set to, one of the {{cPluginManager#CommandResult|CommandResult}} constants. If not
provided, the value defaults to crBlocked.
]],
}, -- HOOK_EXECUTE_COMMAND
}
| apache-2.0 |
LiberatorUSA/GUCEF | tools/CMakeListGenerator/premake4.lua | 1 | 2631 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: CMakeListGenerator
configuration( { "LINUX" } )
project( "CMakeListGenerator" )
configuration( { "WIN32" } )
project( "CMakeListGenerator" )
configuration( { "WIN64" } )
project( "CMakeListGenerator" )
configuration( {} )
location( os.getenv( "PM4OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM4TARGETDIR" ) )
configuration( {} )
language( "C" )
configuration( { "LINUX" } )
language( "C++" )
configuration( { "WIN32" } )
language( "C++" )
configuration( { "WIN64" } )
language( "C++" )
configuration( { "LINUX" } )
configuration( { LINUX } )
kind( "ConsoleApp" )
configuration( { "WIN32" } )
configuration( { WIN32 } )
kind( "WindowedApp" )
configuration( { "WIN64" } )
configuration( { WIN64 } )
kind( "WindowedApp" )
configuration( { LINUX } )
links( { "gucefCORE", "gucefMT" } )
links( { "gucefCORE", "gucefMT" } )
configuration( { LINUX } )
defines( { "CMAKELISTGENERATOR_BUILD_MODULE" } )
configuration( { WIN32 } )
links( { "gucefCORE", "gucefMT" } )
links( { "gucefCORE", "gucefMT" } )
configuration( { WIN32 } )
defines( { "CMAKELISTGENERATOR_BUILD_MODULE" } )
configuration( { WIN64 } )
links( { "gucefCORE", "gucefMT" } )
links( { "gucefCORE", "gucefMT" } )
configuration( { WIN64 } )
defines( { "CMAKELISTGENERATOR_BUILD_MODULE" } )
configuration( { "LINUX" } )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/main.cpp"
} )
configuration( { "WIN32" } )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/main.cpp"
} )
configuration( { "WIN64" } )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/main.cpp"
} )
configuration( {} )
includedirs( { "../../common/include", "../../gucefCORE/include", "../../gucefMT/include" } )
configuration( { "LINUX" } )
includedirs( { "../../gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Ulrike.lua | 53 | 1816 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Ulrike
-- Type: Goldsmithing Synthesis Image Support
-- @pos -218.399 -7.824 -56.203 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,6);
local SkillCap = getCraftSkillCap(player, SKILL_GOLDSMITHING);
local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then
player:startEvent(0x0130,SkillCap,SkillLevel,2,201,player:getGil(),0,9,0);
else
player:startEvent(0x0130,SkillCap,SkillLevel,2,201,player:getGil(),6975,9,0);
end
else
player:startEvent(0x0130);
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 == 0x0130 and option == 1) then
player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,2);
player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
Keithenneu/Dota2-FullOverwrite | global_game_state.lua | 1 | 18732 | _G._savedEnv = getfenv()
module( "global_game_state", package.seeall )
require( GetScriptDirectory().."/buildings_status" )
require( GetScriptDirectory().."/debugging" )
local gHero = require( GetScriptDirectory().."/global_hero_data" )
local utils = require( GetScriptDirectory().."/utility" )
local enemyData = require( GetScriptDirectory().."/enemy_data" )
local laneStates = {[LANE_TOP] = {dontdefend = false},
[LANE_MID] = {dontdefend = false},
[LANE_BOT] = {dontdefend = false}}
local shrineStates = {
[SHRINE_BASE_1] = {handle = GetShrine(GetTeam(), SHRINE_BASE_1), pidsLookingForHeal = {}},
[SHRINE_BASE_2] = {handle = GetShrine(GetTeam(), SHRINE_BASE_2), pidsLookingForHeal = {}},
[SHRINE_BASE_3] = {handle = GetShrine(GetTeam(), SHRINE_BASE_3), pidsLookingForHeal = {}},
[SHRINE_BASE_4] = {handle = GetShrine(GetTeam(), SHRINE_BASE_4), pidsLookingForHeal = {}},
[SHRINE_BASE_5] = {handle = GetShrine(GetTeam(), SHRINE_BASE_5), pidsLookingForHeal = {}},
[SHRINE_JUNGLE_1] = {handle = GetShrine(GetTeam(), SHRINE_JUNGLE_1), pidsLookingForHeal = {}},
[SHRINE_JUNGLE_2] = {handle = GetShrine(GetTeam(), SHRINE_JUNGLE_2), pidsLookingForHeal = {}}
}
function GetShrineState(shrineID)
return shrineStates[shrineID]
end
function RemovePIDFromShrine(shrineID, pid)
local pidLoc = utils.PosInTable(shrineStates[shrineID].pidsLookingForHeal, pid)
if pidLoc >= 0 then
table.remove(shrineStates[shrineID].pidsLookingForHeal, pidLoc)
end
end
-- TODO: used for reading and writing. not really good.
function LaneState(lane)
return laneStates[lane]
end
-- Returns the closest building of team to a unit
function GetClosestBuilding(unit, team)
local min_dist = 99999999
local building = nil
for _, id in pairs(buildings_status.GetStandingBuildingIDs(team)) do
local vec = buildings_status.GetLocation(team, id)
local d = GetUnitToLocationDistance(unit, vec)
if d < min_dist then
min_dist = d
building = vec
end
end
return id, building
end
-- Get the position between buildings (0 = sitting on teams tower, 1 = sitting on enemy's tower)
function GetPositionBetweenBuildings(unit, team)
local _, allied_building = GetClosestBuilding(unit, team)
local d_allied = GetUnitToLocationDistance(unit, allied_building)
local _, enemy_building = GetClosestBuilding(unit, utils.GetOppositeTeamTo(team))
local d_enemy = GetUnitToLocationDistance(unit, enemy_building)
return d_allied / (d_allied + d_enemy)
end
function nearBuilding(unitLoc, buildingLoc)
return utils.GetDistance(unitLoc, buildingLoc) <= 1000
end
function numEnemiesNearBuilding(building)
local num = 0
local enemies = GetUnitList(UNIT_LIST_ENEMY_HEROES)
for _, enemy in pairs(enemies) do
if nearBuilding(enemy:GetLocation(), buildings_status.GetLocation(GetTeam(), building)) then
num = num + 1
end
end
return num
end
-- Detect if a tower is being pushed
function DetectEnemyPushMid()
local building = buildings_status.GetVulnerableBuildingIDs(GetTeam(), LANE_MID)[1]
local hBuilding = buildings_status.GetHandle(GetTeam(), building)
if hBuilding == nil then return 0, building end
if hBuilding and hBuilding:TimeSinceDamagedByAnyHero() < 1.5 then
local num = numEnemiesNearBuilding(building)
return num, building
end
return 0, building
end
function DetectEnemyPushTop()
local building = buildings_status.GetVulnerableBuildingIDs(GetTeam(), LANE_TOP)[1]
local hBuilding = buildings_status.GetHandle(GetTeam(), building)
if hBuilding == nil then return 0, building end
if hBuilding and hBuilding:TimeSinceDamagedByAnyHero() < 1.5 then
local num = numEnemiesNearBuilding(building)
return num, building
end
return 0, building
end
function DetectEnemyPushBot()
local building = buildings_status.GetVulnerableBuildingIDs(GetTeam(), LANE_BOT)[1]
local hBuilding = buildings_status.GetHandle(GetTeam(), building)
if hBuilding == nil then return 0, building end
if hBuilding and hBuilding:TimeSinceDamagedByAnyHero() < 1.5 then
local num = numEnemiesNearBuilding(building)
return num, building
end
return 0, building
end
local lastPushCheck = -1000.0
function DetectEnemyPush()
local bUpdate, newTime = utils.TimePassed(lastPushCheck, 0.5)
if bUpdate then
local numMid, midBuilding = DetectEnemyPushMid()
local numTop, topBuilding = DetectEnemyPushTop()
local numBot, botBuilding = DetectEnemyPushBot()
if numMid > 0 then
return LANE_MID, midBuilding, numMid
elseif numTop > 0 then
return LANE_TOP, topBuilding, numTop
elseif numBot > 0 then
return LANE_BOT, botBuilding, numBot
end
lastPushCheck = newTime
end
return nil, nil, nil
end
local lastBuildingUpdate = -1000.0
local vulnEnemyBuildings = nil
function GetLatestVulnerableEnemyBuildings()
local bUpdate, newTime = utils.TimePassed(lastBuildingUpdate, 3.0)
if bUpdate then
vulnEnemyBuildings = buildings_status.GetDestroyableTowers(utils.GetOtherTeam())
lastBuildingUpdate = newTime
end
return vulnEnemyBuildings
end
local lastGlobalFightDetermination = -1000.0
function GlobalFightDetermination()
local bUpdate, newTime = utils.TimePassed(lastGlobalFightDetermination, 0.25)
if bUpdate then lastGlobalFightDetermination = newTime else return end
local eyeRange = 1200
local listAllies = GetUnitList(UNIT_LIST_ALLIED_HEROES)
for _, ally in pairs(listAllies) do
if ally:IsAlive() and ally:IsBot() and ally:GetHealth()/ally:GetMaxHealth() > 0.4 and not ally:IsIllusion()
and gHero.HasID(ally:GetPlayerID()) and gHero.GetVar(ally:GetPlayerID(), "Target").Id == 0 then
local totalNukeDmg = 0
local numEnemiesThatCanAttackMe = 0
local numAlliesThatCanHelpMe = 0
for k, enemy in pairs(enemyData) do
-- get a valid enemyData enemy
if type(k) == "number" and enemy.Alive then
local distance = 100000
if enemy.Obj then
distance = GetUnitToUnitDistance(ally, enemy.Obj)
else
if GetHeroLastSeenInfo(k).time == -1 then break end
if GetHeroLastSeenInfo(k).time <= 0.5 then
distance = GetUnitToLocationDistance(ally, enemy.LocExtra1)
elseif GetHeroLastSeenInfo(k).time <= 3.0 then
distance = GetUnitToLocationDistance(ally, enemy.LocExtra2)
else
break --distance = GetUnitToLocationDistance(ally, GetHeroLastSeenInfo(k).location)
end
end
local theirTimeToReachMe = distance/enemy.MoveSpeed
local timeToReach = distance/ally:GetCurrentMovementSpeed()
local myNukeDmg, myActionQueue, myCastTime, myStun, mySlow, myEngageDist = gHero.GetVar(ally:GetPlayerID(), "Self"):GetNukeDamage( ally, enemy.Obj )
-- update our total nuke damage
totalNukeDmg = totalNukeDmg + myNukeDmg
if distance <= eyeRange then
numEnemiesThatCanAttackMe = numEnemiesThatCanAttackMe + 1
--utils.myPrint(utils.GetHeroName(ally), " sees "..enemy.Name.." ", distance, " units away. Time to reach: ", timeToReach)
local allAllyStun = 0
local allAllySlow = 0
local myTimeToKillTarget = 0.0
if utils.ValidTarget(enemy) then
myTimeToKillTarget = fight_simul.estimateTimeToKill(ally, enemy.Obj)
else
myTimeToKillTarget = enemy.Health/(ally:GetAttackDamage()/ally:GetSecondsPerAttack())/0.75
end
local totalTimeToKillTarget = myTimeToKillTarget
local participatingAllies = {}
local globalAllies = {}
for _, ally2 in pairs(listAllies) do
-- this 'if' is for non-implemented bot heroes that are on our team
if ally2:IsAlive() and ally2:IsBot() and not ally2:IsIllusion() and not gHero.HasID(ally2:GetPlayerID()) then
local distToEnemy = 100000
if enemy.Obj then
distToEnemy = GetUnitToUnitDistance(ally2, enemy.Obj)
else
if GetHeroLastSeenInfo(k) == nil then break end
if GetHeroLastSeenInfo(k).time <= 0.5 then
distToEnemy = GetUnitToLocationDistance(ally2, enemy.LocExtra1)
elseif GetHeroLastSeenInfo(k).time <= 3.0 then
distToEnemy = GetUnitToLocationDistance(ally2, enemy.LocExtra2)
else
break --distToEnemy = GetUnitToLocationDistance(ally2, GetHeroLastSeenInfo(k).location)
end
end
local allyTimeToReach = distToEnemy/ally2:GetCurrentMovementSpeed()
local globalAbility = gHero.GetVar(ally2:GetPlayerID(), "HasGlobal")
if distToEnemy <= 2*eyeRange then
--utils.myPrint("ally ", utils.GetHeroName(ally2), " is ", distToEnemy, " units away. Time to reach: ", allyTimeToReach)
totalTimeToKillTarget = totalTimeToKillTarget + 8.0
table.insert(participatingAllies, {ally2, {}, 500})
elseif globalAbility and globalAbility[1]:IsFullyCastable() then
table.insert(globalAllies, {ally2, globalAbility})
end
-- this 'elseif' is for implemented bot heroes on our team
elseif ally2:IsAlive() and not ally2:IsIllusion() and ally2:GetPlayerID() ~= ally:GetPlayerID() and gHero.GetVar(ally2:GetPlayerID(), "Target").Id == 0
and (gHero.GetVar(ally2:GetPlayerID(), "GankTarget").Id == 0 or gHero.GetVar(ally2:GetPlayerID(), "GankTarget").Id == k) then
local distToEnemy = 100000
if enemy.Obj then
distToEnemy = GetUnitToUnitDistance(ally2, enemy.Obj)
else
if GetHeroLastSeenInfo(k).time <= 0.5 then
distToEnemy = GetUnitToLocationDistance(ally2, enemy.LocExtra1)
elseif GetHeroLastSeenInfo(k).time <= 3.0 then
distToEnemy = GetUnitToLocationDistance(ally2, enemy.LocExtra2)
else
--distToEnemy = GetUnitToLocationDistance(ally2, GetHeroLastSeenInfo(k).location)
break
end
end
if GetUnitToUnitDistance(ally, ally2) < eyeRange then
numAlliesThatCanHelpMe = numAlliesThatCanHelpMe + 1
end
local allyTimeToReach = distToEnemy/ally2:GetCurrentMovementSpeed()
local allyNukeDmg, allyActionQueue, allyCastTime, allyStun, allySlow, allyEngageDist = gHero.GetVar(ally2:GetPlayerID(), "Self"):GetNukeDamage( ally2, enemy.Obj )
-- update our total nuke damage
totalNukeDmg = totalNukeDmg + allyNukeDmg
local globalAbility = gHero.GetVar(ally2:GetPlayerID(), "HasGlobal")
if allyTimeToReach <= 6.0 then
--utils.myPrint("ally ", utils.GetHeroName(ally2), " is ", distToEnemy, " units away. Time to reach: ", allyTimeToReach)
allAllyStun = allAllyStun + allyStun
allAllySlow = allAllySlow + allySlow
local allyTimeToKillTarget = 0.0
if utils.ValidTarget(enemy) then
allyTimeToKillTarget = fight_simul.estimateTimeToKill(ally2, enemy.Obj)
else
allyTimeToKillTarget = enemy.Health /(ally2:GetAttackDamage()/ally2:GetSecondsPerAttack())/0.75
end
totalTimeToKillTarget = totalTimeToKillTarget + allyTimeToKillTarget
table.insert(participatingAllies, {ally2, allyActionQueue, allyEngageDist})
elseif globalAbility and globalAbility[1]:IsFullyCastable() then
table.insert(globalAllies, {ally2, globalAbility})
end
end
end
local numAttackers = #participatingAllies+1
local anticipatedTimeToKill = (totalTimeToKillTarget/numAttackers) - 2*#globalAllies
local totalStun = myStun + allAllyStun
local totalSlow = mySlow + allAllySlow
local timeToKillBonus = numAttackers*(totalStun + 0.5*totalSlow)
if utils.ValidTarget(enemy) then
-- if global we picked a 1v? fight then let it work out at the hero-level
if numAttackers == 1 then break end
if totalNukeDmg/#gHeroVar.GetNearbyEnemies(ally, 1200) >= enemy.Obj:GetHealth() then
utils.myPrint(#participatingAllies+1, " of us can Nuke ", enemy.Name)
utils.myPrint(utils.GetHeroName(ally), " - Engaging!")
local allyID = ally:GetPlayerID()
gHero.SetVar(allyID, "Target", {Obj=enemy.Obj, Id=k})
gHero.GetVar(allyID, "Self"):AddMode(constants.MODE_FIGHT)
gHero.GetVar(allyID, "Self"):QueueNuke(ally, enemy.Obj, myActionQueue, myEngageDist)
for _, v in pairs(participatingAllies) do
if gHero.GetVar(v[1]:GetPlayerID(), "GankTarget").Id == 0 then
gHero.SetVar(v[1]:GetPlayerID(), "Target", {Obj=enemy.Obj, Id=k})
gHero.GetVar(v[1]:GetPlayerID(), "Self"):AddMode(constants.MODE_FIGHT)
if #v[2] > 0 and GetUnitToUnitDistance(v[1], enemy.Obj) < v[3] then
gHero.GetVar(v[1]:GetPlayerID(), "Self"):QueueNuke(v[1], enemy.Obj, v[2], v[3])
elseif #v[2] > 0 then
gHero.HeroAttackUnit(v[1], enemy.Obj, true)
end
end
end
for _, v in pairs(globalAllies) do
gHero.SetVar(v[1]:GetPlayerID(), "UseGlobal", {v[2][1], enemy.Obj})
utils.myPrint(utils.GetHeroName(v[1]).." casting global skill.")
end
return
elseif (anticipatedTimeToKill - timeToKillBonus) < 6.0/#gHeroVar.GetNearbyEnemies(ally, 1200) then
utils.myPrint(#participatingAllies+#globalAllies+1, " of us can Stun for: ", totalStun, " and Slow for: ", totalSlow, ". AnticipatedTimeToKill ", enemy.Name ,": ", anticipatedTimeToKill)
utils.myPrint(utils.GetHeroName(ally), " - Engaging! Anticipated Time to kill: ", anticipatedTimeToKill)
gHero.SetVar(ally:GetPlayerID(), "Target", {Obj=enemy.Obj, Id=k})
gHero.GetVar(ally:GetPlayerID(), "Self"):AddMode(constants.MODE_FIGHT)
for _, v in pairs(participatingAllies) do
if gHero.GetVar(v[1]:GetPlayerID(), "GankTarget").Id == 0 then
gHero.SetVar(v[1]:GetPlayerID(), "Target", {Obj=enemy.Obj, Id=k})
gHero.GetVar(v[1]:GetPlayerID(), "Self"):AddMode(constants.MODE_FIGHT)
if #v[2] > 0 and GetUnitToUnitDistance(v[1], enemy.Obj) < v[3] then
gHero.GetVar(v[1]:GetPlayerID(), "Self"):QueueNuke(v[1], enemy.Obj, v[2], v[3])
elseif #v[2] > 0 then
gHero.HeroAttackUnit(v[1], enemy.Obj, true)
end
end
end
for _, v in pairs(globalAllies) do
gHero.SetVar(v[1]:GetPlayerID(), "UseGlobal", {v[2][1], enemy.Obj})
utils.myPrint(utils.GetHeroName(v[1]).." casting global skill.")
end
return
end
end
end
end
end
if numEnemiesThatCanAttackMe > numAlliesThatCanHelpMe then
--utils.myPrint(utils.GetHeroName(ally), "This is a bad idea")
--ally:Action_ClearActions(false)
end
end
end
end
for k,v in pairs( global_game_state ) do _G._savedEnv[k] = v end
| gpl-3.0 |
LiberatorUSA/GUCEF | dependencies/cegui/cegui/src/ScriptModules/Lua/support/tolua++bin/lua/typedef.lua | 15 | 1694 | -- tolua: typedef class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Typedef class
-- Represents a type synonym.
-- The 'de facto' type replaces the typedef before the
-- remaining code is parsed.
-- The following fields are stored:
-- utype = typedef name
-- type = 'the facto' type
-- mod = modifiers to the 'de facto' type
classTypedef = {
utype = '',
mod = '',
type = ''
}
classTypedef.__index = classTypedef
-- Print method
function classTypedef:print (ident,close)
print(ident.."Typedef{")
print(ident.." utype = '"..self.utype.."',")
print(ident.." mod = '"..self.mod.."',")
print(ident.." type = '"..self.type.."',")
print(ident.."}"..close)
end
-- Return it's not a variable
function classTypedef:isvariable ()
return false
end
-- Internal constructor
function _Typedef (t)
setmetatable(t,classTypedef)
t.type = resolve_template_types(t.type)
appendtypedef(t)
return t
end
-- Constructor
-- Expects one string representing the type definition.
function Typedef (s)
if strfind(string.gsub(s, '%b<>', ''),'[%*&]') then
tolua_error("#invalid typedef: pointers (and references) are not supported")
end
local o = {mod = ''}
if string.find(s, "[<>]") then
_,_,o.type,o.utype = string.find(s, "^%s*([^<>]+%b<>[^%s]*)%s+(.-)$")
else
local t = split(gsub(s,"%s%s*"," ")," ")
o = {
utype = t[t.n],
type = t[t.n-1],
mod = concat(t,1,t.n-2),
}
end
return _Typedef(o)
end
| apache-2.0 |
jshackley/darkstar | scripts/globals/items/serving_of_salmon_eggs.lua | 35 | 1340 | -----------------------------------------
-- ID: 5217
-- Item: serving_of_salmon_eggs
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 6
-- Magic 6
-- Dexterity 2
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5217);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 6);
target:addMod(MOD_MP, 6);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 6);
target:delMod(MOD_MP, 6);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -3);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Mhaura/npcs/Explorer_Moogle.lua | 17 | 1783 | -----------------------------------
-- Area: Mhaura
-- NPC: Explorer Moogle
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local accept = 0;
local event = 0x014e;
if (player:getGil() < 300) then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZoneID(),0,accept);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
local price = 300;
if (csid == 0x014e) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
botmohammad12344888/bot-888338888 | plugins/dic.lua | 2 | 1530 | do
function translate(source_lang, target_lang, text)
local path = "http://translate.google.com/translate_a/single"
-- URL query parameters
local params = {
client = "t",
ie = "UTF-8",
oe = "UTF-8",
hl = "en",
dt = "t",
tl = target_lang or "en",
sl = source_lang or "auto",
text = URL.escape(text)
}
local query = format_http_params(params, true)
local url = path..query
local res, code = https.request(url)
-- Return nil if error
if code > 200 then return nil end
local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
return trans
end
function run(msg, matches)
-- Third pattern
if #matches == 1 then
print("First")
local text = matches[1]
return translate(nil, nil, text)
end
-- Second pattern
if #matches == 2 then
print("Second")
local target = matches[1]
local text = matches[2]
return translate(nil, target, text)
end
-- First pattern
if #matches == 3 then
print("Third")
local source = matches[1]
local target = matches[2]
local text = matches[3]
return translate(source, target, text)
end
end
return {
description = "Translate some text",
usage = {
"ترجمه text. Translate the text to English.",
"ترجمه target_lang text.",
"ترجمه source,target text",
},
patterns = {
"^ترجمه ([%w] ),([%a] ) (. )",
"^ترجمه ([%w] ) (. )",
"^ترجمه (. )",
},
run = run
}
end
| gpl-2.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsJointRotarySpring.lua | 6 | 1379 |
--------------------------------
-- @module PhysicsJointRotarySpring
-- @extend PhysicsJoint
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] getDamping
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] setRestAngle
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] getStiffness
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] setStiffness
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] setDamping
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] getRestAngle
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#PhysicsJointRotarySpring] construct
-- @param self
-- @param #cc.PhysicsBody physicsbody
-- @param #cc.PhysicsBody physicsbody
-- @param #float float
-- @param #float float
-- @return PhysicsJointRotarySpring#PhysicsJointRotarySpring ret (return value: cc.PhysicsJointRotarySpring)
return nil
| mit |
kodewulf/GenesisEngine | classes/cConsole.lua | 1 | 4116 | local B = require('cClass')
local C = B:extends()
C._NAME = 'Console'
C._ID = 'console'
C.__name = C._ID
-- CONSOLE._SIMULATOR = ("simulator" == system.getInfo("environment")) or false -- Only run in simulator
local function consoleParamCheck(paramCheck)
if (not paramCheck) then return end
local params = paramCheck
if (type(paramCheck) ~= "table") then
params = {}
params.message = tostring(paramCheck)
end
return params
end
function C:print(args)
if (args == nil) then return end
if (args.verbose == false) then return end
local config = {}
config.Verbose = self:getConfig('Console/Verbose', 'info')
local consoleVerbose = config.Verbose or 'info'
if (consoleVerbose == "none") then return end
args = consoleParamCheck(args)
if (args.verbose == nil) then args.verbose = true end
if (args.msgType == nil) then args.msgType = "debug" end
if (consoleVerbose == "info") then args.verbose = (args.msgType == "info") end
if (consoleVerbose == "warn") then args.verbose = ((args.msgType == "info") or (args.msgType == "warn")) end
if (consoleVerbose == "error") then args.verbose = ((args.msgType == "info") or (args.msgType == "warn") or (args.msgType == "error")) end
if (consoleVerbose == "critical") then args.verbose = ((args.msgType == "info") or (args.msgType == "warn") or (args.msgType == "error") or (args.msgType == "critical")) end
if (consoleVerbose == "debug") then args.verbose = ((args.msgType == "info") or (args.msgType == "warn") or (args.msgType == "error") or (args.msgType == "critical") or (args.msgType == "debug")) end
if (args.force == true) then args.verbose = true end
if (args.verbose == false) then return end
if (args.source == nil) then args.source = {} end
-- Initialise message variable
local message = ""
-- Add message type
if (args.msgType == 'info') then
message = "[INFO] "
elseif (args.msgType == 'warn') then
message = "[WARN] "
elseif (args.msgType == 'error') then
message = "[ERROR] "
elseif (args.msgType == 'critical') then
message = "[CRITICAL] "
elseif (args.msgType == 'debug') then
message = "[DEBUG] "
end
-- Add source name
if (args.source.name ~= nil) then
message = message .. "<" .. args.source.name .. "> "
end
-- Add Message
message = message .. args.message
-- Override message with empty string if needed
if (args.message:len() == 0) then message = "" end
print(message)
return message
end
function C:printDebug(args)
args = consoleParamCheck(args)
args.msgType = 'debug'
if (args.source == nil) then
args.source = {name = self._NAME}
end
if (args.source.name == nil) then args.source.name = self._NAME end
self:print(args)
end
function C:printInfo(args)
args = consoleParamCheck(args)
args.msgType = 'info'
self:print(args)
end
function C:printWarn(args)
args = consoleParamCheck(args)
args.msgType = 'warn'
self:print(args)
end
function C:printError(args)
args = consoleParamCheck(args)
args.msgType = 'error'
self:print(args)
end
function C:printCritical(args)
args = consoleParamCheck(args)
args.msgType = 'critical'
self:print(args)
end
function C:printTable(tbl)
self:printDebug("-=[ TABLE START ]=-")
for k, v in pairs(tbl) do
if (type(v) == "table") then
self:printTable(v, "[" .. tostring(k) .. "]")
else
self:printDebug("[" .. tostring(k) .. "] => " .. tostring(v))
end
end
self:printDebug("-=[ TABLE END ]=-")
end
function C:printVersion()
local version = self:getVersionInfoString()
self:printInfo(version)
end
function C:__init(params)
C.super.__init(self, params)
-- self:setConfig('Console/Verbose', 'info')
-- self:setConfig('Console/Simulator', ("simulator" == system.getInfo("environment")) or false)
-- self:PrintDebug("__init")
end
return C
| mit |
jshackley/darkstar | scripts/zones/Nashmau/npcs/Jajaroon.lua | 34 | 1593 | -----------------------------------
-- Area: Nashmau
-- NPC: Jajaroon
-- 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,JAJAROON_SHOP_DIALOG);
stock = {0x0880,48, -- Fire Card
0x0881,48, -- Ice Card
0x0882,48, -- Wind Card
0x0883,48, -- Earth Card
0x0884,48, -- Thunder Card
0x0885,48, -- Water Card
0x0886,48, -- Light Card
0x0887,48, -- Dark Card
0x16ee,10000, -- Trump Card Case
0x1570,35200, -- Samurai Die
0x1571,600, -- Ninja Die
0x1572,82500, -- Dragoon Die
0x1573,40000, -- Summoner Die
0x1574,3525, -- Blue Mage Die
0x1575,316, -- Corsar Die
0x1576,9216} -- Puppetmaster 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 |
jshackley/darkstar | scripts/zones/Xarcabard/npcs/Kaya_IM.lua | 30 | 3036 | -----------------------------------
-- Area: Xarcabard
-- NPC: Kaya, I.M.
-- Type: Outpost Conquest Guards
-- @pos 207.548 -24.795 -203.694 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VALDEAUNIA;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/homemade_rice_ball.lua | 35 | 1129 | -----------------------------------------
-- ID: 5224
-- Item: homemade_rice_ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5224);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Upper_Delkfutts_Tower/mobs/Autarch.lua | 8 | 1583 | -----------------------------------
-- Area: Upper Delkfutt's Tower
-- NM: Autarch
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_AUTO_SPIKES,mob:getShortID());
mob:addStatusEffect(EFFECT_SHOCK_SPIKES,40,0,0);
mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32);
end;
-----------------------------------
-- onSpikesDamage
-----------------------------------
function onSpikesDamage(mob,target,damage)
local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT);
if (INT_diff > 20) then
INT_diff = 20 + ((INT_diff - 20)*0.5); -- INT above 20 is half as effective.
end
local dmg = ((damage+INT_diff)*0.5); -- INT adjustment and base damage averaged together.
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(mob, ELE_THUNDER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(mob,target,ELE_THUNDER,0);
dmg = adjustForTarget(target,dmg,ELE_THUNDER);
dmg = finalMagicNonSpellAdjustments(mob,target,ELE_THUNDER,dmg);
if (dmg < 0) then
dmg = 0;
end
return SUBEFFECT_SHOCK_SPIKES,44,dmg;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
-- UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random(7200,10800)); -- 2 to 3 hrs
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/North_Gustaberg/npcs/relic.lua | 38 | 1851 | -----------------------------------
-- Area: North Gustaberg
-- NPC: <this space intentionally left blank>
-- @pos -217 97 461 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/North_Gustaberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18305 and trade:getItemCount() == 4 and trade:hasItemQty(18305,1) and
trade:hasItemQty(1577,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then
player:startEvent(254,18306);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 == 254) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18306);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450);
else
player:tradeComplete();
player:addItem(18306);
player:addItem(1450,30);
player:messageSpecial(ITEM_OBTAINED,18306);
player:messageSpecial(ITEMS_OBTAINED,1450,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/garpike.lua | 18 | 1256 | -----------------------------------------
-- ID: 5472
-- Item: Garpike
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5472);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Cloister_of_Flames/bcnms/trial_by_fire.lua | 19 | 1773 | -----------------------------------
-- Area: Cloister of Flames
-- BCNM: Trial by Fire
-- @pos -721 0 -598 207
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Cloister_of_Flames/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompleteQuest(OUTLANDS,TRIAL_BY_FIRE)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:delKeyItem(TUNING_FORK_OF_FIRE);
player:addKeyItem(WHISPER_OF_FLAMES);
player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_FLAMES);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Port_San_dOria/npcs/Bonarpant.lua | 36 | 1375 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Bonarpant
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x253);
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 |
jshackley/darkstar | scripts/globals/items/tortilla_bueno.lua | 35 | 1193 | -----------------------------------------
-- ID: 5181
-- Item: tortilla_bueno
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 8
-- Vitality 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5181);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_VIT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_VIT, 4);
end;
| gpl-3.0 |
kjmac123/metabuilder | metabuilder/metabuilder.lua | 1 | 1244 | solution "metabuilder"
import "solution_windows.lua"
target "metabuilder"
target_type "app"
target_subsystem "console"
--build against Lua library
depends("lua", "../external/lua-5.2.2/metabuilder.lua")
defines
{
}
includedirs
{
"src",
"../external/dlmalloc-2.8.6",
"../external/ezOptionParser-0.2.1",
"../external/lua-5.2.2/src",
"../external",
}
files
{
"src/platform/platform.cpp",
"src/block.cpp",
"src/common.cpp",
"src/configparam.cpp",
"src/core.cpp",
"src/corestring.cpp",
"src/filepath.cpp",
"src/luafile.cpp",
"src/main.cpp",
"src/makeglobal.cpp",
"src/mbstring.cpp",
"src/metabase.cpp",
"src/metabuilder_pch.cpp",
"src/platformparam.cpp",
"src/solution.cpp",
"src/target.cpp",
"src/timeutil.cpp",
"src/writer.cpp",
"src/writer_msvc.cpp",
"src/writer_utility.cpp",
"src/writer_xcode.cpp",
"metabuilder.lua",
"metabuilder_posix.lua",
"metabuilder_windows.lua",
}
--build configurations
config "Debug"
defines
{
}
config_end()
config "Release"
defines
{
}
config_end()
import "metabuilder_posix.lua"
import "metabuilder_windows.lua"
target_end()
solution_end()
| mit |
LiberatorUSA/GUCEF | platform/gucefMATH/premake4.lua | 1 | 2240 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: gucefMATH
project( "gucefMATH" )
configuration( {} )
location( os.getenv( "PM4OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM4TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "gucefCORE", "gucefMT" } )
links( { "gucefCORE", "gucefMT" } )
configuration( {} )
defines( { "GUCEF_MATH_BUILD_MODULE" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/gucefMATH.h",
"include/gucefMATH_CModule.h",
"include/gucefMATH_config.h",
"include/gucefMATH_CTDirectionVector2D.h",
"include/gucefMATH_CTDirectionVector3D.h",
"include/gucefMATH_CTMatrix3D.h",
"include/gucefMATH_CTMatrix4D.h",
"include/gucefMATH_CTPoint2D.h",
"include/gucefMATH_CTPoint3D.h",
"include/gucefMATH_CTSpace.h",
"include/gucefMATH_CTVector1D.h",
"include/gucefMATH_CTVector2D.h",
"include/gucefMATH_CTVector3D.h",
"include/gucefMATH_ETypes.h",
"include/gucefMATH_macros.h",
"include/gucefMATH_points.h",
"include/gucefMATH_vectors.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/gucefMATH_CModule.cpp"
} )
configuration( {} )
includedirs( { "../common/include", "../gucefCORE/include", "../gucefMT/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../gucefCORE/include/android" } )
configuration( { "LINUX" } )
includedirs( { "../gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/Attohwa_Chasm/mobs/Sargas.lua | 1 | 2177 | -----------------------------------
-- Area: Attohwa Chasm
-- NM: Sargas
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
mob:setMobMod(MOBMOD_AUTO_SPIKES,mob:getShortID());
mob:addStatusEffect(EFFECT_SHOCK_SPIKES,50,0,0);
mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32);
end;
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(mob,target,damage)
-- Guestimating 2 in 3 chance to stun on melee.
if ((math.random(1,100) >= 66) or (target:hasStatusEffect(EFFECT_STUN) == true)) then
return 0,0,0;
else
local duration = math.random(5,15);
target:addStatusEffect(EFFECT_STUN,5,0,duration);
return SUBEFFECT_STUN,0,EFFECT_STUN;
end
end;
-----------------------------------
-- onSpikesDamage
-----------------------------------
function onSpikesDamage(mob,target,damage)
local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT);
if (INT_diff > 20) then
INT_diff = 20 + ((INT_diff - 20)*0.5); -- INT above 20 is half as effective.
end
local dmg = ((damage+INT_diff)*0.5); -- INT adjustment and base damage averaged together.
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(mob, ELE_THUNDER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(mob,target,ELE_THUNDER,0);
dmg = adjustForTarget(target,dmg,ELE_THUNDER);
dmg = finalMagicNonSpellAdjustments(mob,target,ELE_THUNDER,dmg);
if (dmg < 0) then
dmg = 0;
end
return SUBEFFECT_SHOCK_SPIKES,44,dmg;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
-- UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random((7200),(10800))); -- 2 to 3 hrs
end; | gpl-3.0 |
DarkRainX/ufoai | base/ufos/ui/market.components.lua | 2 | 5256 | --!usr/bin/lua
require("ufox.lua")
-- Market category label
do
local MarketCategory = ufox.build_component({
name = "MarketCategory",
class = "panel",
size = {713, 28},
backgroundcolor = {0.56, 0.81, 0.76, 0.3},
on_mouseenter = function (sender)
sender:set_backgroundcolor(0.56, 0.81, 0.76, 0.4)
end,
on_mouseleave = function (sender)
sender:set_backgroundcolor(0.56, 0.81, 0.76, 0.3)
end,
{
name = "name",
class = "string",
pos = {30, 0},
size = {400, 28},
color = {0.56, 0.81, 0.76, 1},
contentalign = ufo.ALIGN_CL,
ghost = true,
},
})
end
-- Market category list
do
local MarketList = ufox.build_component({
name = "MarketList",
class = "panel",
size = {713, 0},
layout = ufo.LAYOUT_TOP_DOWN_FLOW,
layoutmargin = 2,
})
end
-- Market item
do
local MarketItem = ufox.build_component({
name = "MarketItem",
class = "panel",
pos = {0, 0},
size = {713, 28},
backgroundcolor = {0.56, 0.81, 0.76, 0.1},
on_mouseenter = function (sender)
sender:set_backgroundcolor(0.56, 0.81, 0.76, 0.15)
end,
on_mouseleave = function (sender)
sender:set_backgroundcolor(0.56, 0.81, 0.76, 0.1)
end,
on_click = function (sender)
ufo.cmd(string.format("ui_market_select %q;", sender:child("id"):as_string()))
end,
{
name = "id",
class = "data",
},
{
name = "rate",
class = "data",
value = 1,
},
-- UFOPaedia link for each item
{
name = "ufopaedia",
class = "button",
icon = "icons/windowinfo",
tooltip = "_View UFOPaedia entry",
pos = {5, 5},
size = {18, 18},
on_click = function (sender)
ufo.cmd(string.format("ui_market_showinfo %q;", sender:parent():child("id"):as_string()))
ufo.cmd("ui_market_openpedia;")
end,
},
{
name = "name",
class = "string",
pos = {30, 0},
size = {290, 28},
color = {0.56, 0.81, 0.76, 0.7},
contentalign = ufo.ALIGN_CL,
ghost = true,
},
{
name = "base",
class = "string",
pos = {320, 0},
size = {80, 28},
color = {0.56, 0.81, 0.76, 1},
contentalign = ufo.ALIGN_CR,
ghost = true,
},
-- Buy items
{
name = "buy",
class = "spinner",
pos = {406, 6},
size = {74, 16},
topicon = "icons/arrowtext_lft",
mode = ufo.SPINNER_ONLY_INCREASE,
delta = 1,
shiftmultiplier = 10,
on_mouseenter = function (sender)
sender:set_topicon("icons/arrowtext_lft0")
end,
on_mouseleave = function (sender)
sender:set_topicon("icons/arrowtext_lft")
end,
activate = function (sender)
-- ufo.print(string.format("Change: min: %i current: %i max: %i delta: %i lastdiff: %i\n", sender:min(), sender:value(), sender:max(), sender:delta(), sender:lastdiff()))
ufo.cmd(string.format("ui_market_buy \"%s\" %s;", sender:parent():child("id"):as_string(), tostring(sender:lastdiff())))
ufo.cmd(string.format("ui_market_fill %s;", ufo.findvar("ui_market_category"):as_string()))
ufo.cmd(string.format("ui_market_select \"%s\";", sender:parent():child("id"):as_string()))
end,
},
{
name = "buy_price",
class = "string",
pos = {406, 6},
size = {74, 16},
color = {0, 0, 0, 1},
font = "f_verysmall_bold",
contentalign = ufo.ALIGN_CR,
ghost = true,
},
{
name = "autosell",
class = "checkbox",
tooltip = "_Lock current stock level",
value = 0,
iconchecked = "icons/windowlock",
iconunchecked = "icons/windowlock_light",
iconunknown = "icons/windowlock_light",
pos = {484, 5},
size = {18, 18},
invisible = false,
on_mouseenter = function (sender)
sender:set_iconunchecked("icons/windowlock")
end,
on_mouseleave = function (sender)
sender:set_iconunchecked("icons/windowlock_light")
end,
on_click = function (sender)
ufo.cmd(string.format("ui_market_setautosell \"%s\" %s;", sender:parent():child("id"):as_string(), tostring(sender:as_integer())))
end,
},
-- Sell items
{
name = "sell",
class = "spinner",
pos = {508, 6},
size = {74, 16},
topicon = "icons/arrowtext_rgt",
mode = ufo.SPINNER_ONLY_DECREASE,
delta = 1,
shiftmultiplier = 10,
on_mouseenter = function (sender)
sender:set_topicon("icons/arrowtext_rgt0")
end,
on_mouseleave = function (sender)
sender:set_topicon("icons/arrowtext_rgt")
end,
activate = function (sender)
-- ufo.print(string.format("Change: min: %i current: %i max: %i delta: %i lastdiff: %i\n", sender:min(), sender:value(), sender:max(), sender:delta(), sender:lastdiff()))
ufo.cmd(string.format("ui_market_buy \"%s\" %s;", sender:parent():child("id"):as_string(), tostring(sender:lastdiff())))
ufo.cmd(string.format("ui_market_fill %s;", ufo.findvar("ui_market_category"):as_string()))
ufo.cmd(string.format("ui_market_select \"%s\";", sender:parent():child("id"):as_string()))
end,
},
{
name = "sell_price",
class = "string",
pos = {508, 6},
size = {74, 16},
color = {0, 0, 0, 1},
font = "f_verysmall_bold",
contentalign = ufo.ALIGN_CL,
ghost = true,
},
-- Count of items in the market
{
name = "market",
class = "string",
pos = {586, 0},
size = {100, 28},
color = {0.56, 0.81, 0.76, 1},
contentalign = ufo.ALIGN_CL,
ghost = true,
},
})
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Dynamis-Tavnazia/npcs/qm1.lua | 19 | 2211 | -----------------------------------
-- Area: Dynamis-Tavnazia
-- NPC: ???
-- @pos
-----------------------------------
package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Tavnazia/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (GetServerVariable("[DynaTavnazia]Boss_Trigger")== 0 and trade:getItemCount() == 1 and trade:hasItemQty(3459,1) ) then
local npcX = npc:getXPos();
local npcY = npc:getYPos();
local npcZ = npc:getZPos();
local DiabolosID = TavnaziaDiabolosList[math.random(1,4)];
local ShortID = GetMobByID(DiabolosID):getShortID()
SpawnMob(DiabolosID):updateClaim(player);
GetMobByID(DiabolosID):setMobMod(MOBMOD_SUPERLINK,ShortID);
GetMobByID(DiabolosID):setPos(npcX-1,npcY-2,npcZ-1);
GetMobByID(DiabolosID):setSpawn(npcX-1,npcY-2,npcZ-1);
--printf("DiabolosID: %u",DiabolosID);
if (DiabolosID == 16949252) then -- diabolos smn
SpawnMob(16949253):setMobMod(MOBMOD_SUPERLINK, ShortID);
GetMobByID(16949253):setPos(npcX-1,npcY-2,npcZ-1);
GetMobByID(16949253):setSpawn(npcX-1,npcY-2,npcZ-1);
SpawnMob(16949254):setMobMod(MOBMOD_SUPERLINK, ShortID);
GetMobByID(16949254):setPos(npcX-3,npcY-2,npcZ-1);
GetMobByID(16949254):setSpawn(npcX+3,npcY-2,npcZ-1);
end
SetServerVariable("[DynaTavnazia]Boss_Trigger",1);
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(DIABOLOS,3459);
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 |
HugoBDesigner/love.gradient | gradient.lua | 1 | 3645 | love.gradient = {}
love.gradient.types = {"linear", "radial", "angle", "rhombus", "square"}
love.gradient.images = {}
for _, v in ipairs(love.gradient.types) do
local img = love.image.newImageData(512, 512)
for x = 0, img:getWidth()-1 do
for y = 0, img:getHeight()-1 do
local r, g, b, a = 1, 1, 1, 0
if v == "linear" then
a = x / (img:getWidth()-1)
elseif v == "radial" then
local d = math.sqrt( (x-img:getWidth()/2)^2 + (y-img:getHeight()/2)^2 )
a = 1-math.min(1, d/(img:getWidth()/2) )
elseif v == "angle" then
local angle = -math.atan2(y-img:getHeight()/2, x-img:getWidth()/2) % (math.pi*2)
a = angle/(math.pi*2)
elseif v == "rhombus" then
local px = x >= img:getWidth()/2 and img:getWidth()-x or x
local py = y >= img:getHeight()/2 and img:getHeight()-y or y
a = math.min(1, px + py - img:getWidth()/2 )/( img:getWidth()/2 )
elseif v == "square" then
local px = x >= img:getWidth()/2 and img:getWidth()-x or x
local py = y >= img:getHeight()/2 and img:getHeight()-y or y
a = math.min(px, py) / (img:getWidth()/2)
end
img:setPixel(x, y, r, g, b, a)
end
end
love.gradient.images[v] = love.graphics.newImage(img)
end
function love.gradient.draw(drawFunc, gradientType, centerX, centerY, radialWidth, radialHeight, color1, color2, angle, scaleX, scaleY)
angle = angle or 0
scaleX = scaleX or 1
scaleY = scaleY or 1
--Huge, detailed error handler
assert(type(drawFunc) == "function",
"Gradient's argument #1 must be a drawing function.")
assert(type(gradientType) == "string",
"Gradient's argument #1 must be a gradient type (" .. table.concat(love.gradient.types, ", ") .. ").")
gradientType = string.lower(gradientType) -- For convenience
local containsGradientType = false
for _, v in ipairs(love.gradient.types) do
if v == gradientType then
containsGradientType = true
break
end
end
assert(containsGradientType,
"Gradient's argument #2 must be a gradient type (" .. table.concat(love.gradient.types, ", ") .. ").")
assert(type(centerX) == "number",
"Gradient's argument #3 must be a number (the central point's X coordinate).")
assert(type(centerY) == "number",
"Gradient's argument #4 must be a number (the central point's Y coordinate).")
assert(type(radialWidth) == "number",
"Gradient's argument #5 must be a number (the gradient's radial width).")
assert(type(radialHeight) == "number",
"Gradient's argument #6 must be a number (the gradient's radial height).")
assert(pcall(love.graphics.setColor, color1),
"Gradient's argument #7 must be a valid color table.")
assert(pcall(love.graphics.setColor, color2),
"Gradient's argument #8 must be a valid color table.")
assert(type(angle) == "number",
"Gradient's argument #9 must be a number (the gradient's angle) or nil (default: 0).")
assert(type(scaleX) == "number",
"Gradient's argument #10 must be a number (the gradient's X scale) or nil (default: 1).")
assert(type(scaleY) == "number",
"Gradient's argument #11 must be a number (the gradient's Y scale) or nil (default: 1).")
love.graphics.push("all")
love.graphics.setColor(color1)
drawFunc() -- Sneaky sneaky!
love.graphics.stencil(drawFunc)
love.graphics.setStencilTest()
love.graphics.translate(centerX, centerY)
if angle ~= 0 then
love.graphics.rotate(angle)
end
love.graphics.setColor(color2)
local gradientImg = love.gradient.images[gradientType]
love.graphics.draw(gradientImg, -radialWidth, -radialHeight, 0,
radialWidth * 2 * scaleX / gradientImg:getWidth(), radialHeight * 2 * scaleY / gradientImg:getHeight())
love.graphics.pop()
love.graphics.setStencilTest()
end
| unlicense |
anonymous12212020/mahdi0000 | plugins/anti_fosh.lua | 49 | 1591 | local function run(msg, matches)
if is_owner(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['antifosh'] then
lock_fosh = data[tostring(msg.to.id)]['settings']['antifosh']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_fosh == "yes" then
send_large_msg(chat, 'بدلیل فحاشی از گروه سیکتیر شدید')
chat_del_user(chat, user, ok_cb, true)
end
end
return {
patterns = {
"کس(.*)",
"کون(.*)",
"کیر(.*)",
"ممه(.*)",
"سکس(.*)",
"سیکتیر(.*)",
"قهبه(.*)",
"بسیک(.*)",
"بیناموس(.*)",
"اوبی(.*)",
"کونی(.*)",
"بیشرف(.*)",
"کس ننه(.*)",
"ساک(.*)",
"کیری(.*)",
"خار کوسه(.*)",
"ننه(.*)",
"خواهرتو(.*)",
"سکسی(.*)",
"کسکش(.*)",
"سیک تیر(.*)",
"گاییدم(.*)",
"میگام(.*)",
"میگامت(.*)",
"بسیک(.*)",
"خواهرت(.*)",
"خارتو(.*)",
"کونت(.*)",
"کوست(.*)",
"شورت(.*)",
"سگ(.*)",
"کیری(.*)",
"دزد(.*)",
"ننت(.*)",
"ابمو(.*)",
"جق(.*)"
},
run = run
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است--
| gpl-2.0 |
LiberatorUSA/GUCEF | plugins/GUI/guidriverCEGUI/premake5.lua | 1 | 5615 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: guidriverCEGUI
project( "guidriverCEGUI" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "CEGUI", "freetype", "gucefCORE", "gucefGUI", "gucefINPUT", "gucefMT", "gucefVFS" } )
links( { "CEGUI", "freetype", "gucefCORE", "gucefGUI", "gucefINPUT", "gucefMT", "gucefVFS" } )
configuration( {} )
defines( { "GUIDRIVERCEGUI_BUILD_MODULE" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/guidriverCEGUI.h",
"include/guidriverCEGUI_CButtonImp.h",
"include/guidriverCEGUI_CCEGUIInputAdapter.h",
"include/guidriverCEGUI_CCEGuiDriver.h",
"include/guidriverCEGUI_CCheckboxImp.h",
"include/guidriverCEGUI_CComboboxImp.h",
"include/guidriverCEGUI_CEditboxImp.h",
"include/guidriverCEGUI_CFileOpenDialogImp.h",
"include/guidriverCEGUI_CFileSaveDialogImp.h",
"include/guidriverCEGUI_CFileSystemDialogImp.h",
"include/guidriverCEGUI_CFormBackendImp.h",
"include/guidriverCEGUI_CGUIContext.h",
"include/guidriverCEGUI_CGridViewImp.h",
"include/guidriverCEGUI_CImageFrameImp.h",
"include/guidriverCEGUI_CLabelImp.h",
"include/guidriverCEGUI_CListBoxImp.h",
"include/guidriverCEGUI_CLogAdapter.h",
"include/guidriverCEGUI_CMemoboxImp.h",
"include/guidriverCEGUI_CMenuBarImp.h",
"include/guidriverCEGUI_CModule.h",
"include/guidriverCEGUI_CPopupMenuImp.h",
"include/guidriverCEGUI_CProgressBarImp.h",
"include/guidriverCEGUI_CPushButtonImp.h",
"include/guidriverCEGUI_CRenderContextImp.h",
"include/guidriverCEGUI_CSpinnerImp.h",
"include/guidriverCEGUI_CTabContentPaneImp.h",
"include/guidriverCEGUI_CTabControlImp.h",
"include/guidriverCEGUI_CTreeviewImp.h",
"include/guidriverCEGUI_CVFSInfoProvider.h",
"include/guidriverCEGUI_CWidgetImp.h",
"include/guidriverCEGUI_CWindowImp.h",
"include/guidriverCEGUI_ETypes.h",
"include/guidriverCEGUI_ImageCodecAdapter.h",
"include/guidriverCEGUI_VFSResourceProvider.h",
"include/guidriverCEGUI_XMLParserAdapter.h",
"include/guidriverCEGUI_config.h",
"include/guidriverCEGUI_macros.h",
"include/guidriverCEGUI_pluginAPI.h",
"include/guidriverCEGUI_widgets.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/guidriverCEGUI.cpp",
"src/guidriverCEGUI_CButtonImp.cpp",
"src/guidriverCEGUI_CCEGUIInputAdapter.cpp",
"src/guidriverCEGUI_CCEGuiDriver.cpp",
"src/guidriverCEGUI_CCheckboxImp.cpp",
"src/guidriverCEGUI_CComboboxImp.cpp",
"src/guidriverCEGUI_CEditboxImp.cpp",
"src/guidriverCEGUI_CFileOpenDialogImp.cpp",
"src/guidriverCEGUI_CFileSaveDialogImp.cpp",
"src/guidriverCEGUI_CFileSystemDialogImp.cpp",
"src/guidriverCEGUI_CFormBackendImp.cpp",
"src/guidriverCEGUI_CGUIContext.cpp",
"src/guidriverCEGUI_CGridViewImp.cpp",
"src/guidriverCEGUI_CImageFrameImp.cpp",
"src/guidriverCEGUI_CLabelImp.cpp",
"src/guidriverCEGUI_CListboxImp.cpp",
"src/guidriverCEGUI_CLogAdapter.cpp",
"src/guidriverCEGUI_CMemoboxImp.cpp",
"src/guidriverCEGUI_CMenuBarImp.cpp",
"src/guidriverCEGUI_CModule.cpp",
"src/guidriverCEGUI_CPopupMenuImp.cpp",
"src/guidriverCEGUI_CProgressBarImp.cpp",
"src/guidriverCEGUI_CPushButtonImp.cpp",
"src/guidriverCEGUI_CRenderContextImp.cpp",
"src/guidriverCEGUI_CSpinnerImp.cpp",
"src/guidriverCEGUI_CTabContentPaneImp.cpp",
"src/guidriverCEGUI_CTabControlImp.cpp",
"src/guidriverCEGUI_CTreeviewImp.cpp",
"src/guidriverCEGUI_CVFSInfoProvider.cpp",
"src/guidriverCEGUI_CWidgetImp.cpp",
"src/guidriverCEGUI_CWindowImp.cpp",
"src/guidriverCEGUI_ImageCodecAdapter.cpp",
"src/guidriverCEGUI_VFSResourceProvider.cpp",
"src/guidriverCEGUI_XMLParserAdapter.cpp",
"src/guidriverCEGUI_pluginAPI.cpp",
"src/guidriverCEGUI_widgets.cpp"
} )
configuration( {} )
includedirs( { "../../../common/include", "../../../dependencies/cegui/cegui/include", "../../../dependencies/freetype/include", "../../../dependencies/freetype/include/freetype", "../../../dependencies/freetype/include/freetype/config", "../../../dependencies/freetype/include/freetype/internal", "../../../dependencies/freetype/include/freetype/internal/services", "../../../dependencies/freetype/src", "../../../dependencies/freetype/src/winfonts", "../../../platform/gucefCORE/include", "../../../platform/gucefGUI/include", "../../../platform/gucefIMAGE/include", "../../../platform/gucefINPUT/include", "../../../platform/gucefMT/include", "../../../platform/gucefVFS/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../../../platform/gucefCORE/include/android" } )
configuration( { "LINUX32" } )
includedirs( { "../../../platform/gucefCORE/include/linux" } )
configuration( { "LINUX64" } )
includedirs( { "../../../platform/gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../../platform/gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../../platform/gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/Vunkerl_Inlet_[S]/npcs/Leadavox.lua | 31 | 1758 | -----------------------------------
-- Area: Vunkerl Inlet (S) (I-6)
-- NPC: Leadavox
-- Involved in Quests
-- @pos 206 -32 316
-----------------------------------
package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil;
package.loaded["scripts/globals/quests"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(CRYSTAL_WAR,BETTER_PART_OF_VALOR) == QUEST_ACCEPTED and player:getVar("BetterPartOfValProg") == 3) then
if (trade:hasItemQty(2521,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then
player:startEvent(0x0067);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR,BETTER_PART_OF_VALOR) == QUEST_ACCEPTED) then
if (player:getVar("BetterPartOfValProg") == 2) then
player:startEvent(0x0065);
elseif (player:getVar("BetterPartOfValProg") == 3) then
player:startEvent(0x0066);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0065) then
player:setVar("BetterPartOfValProg",3);
elseif (csid == 0x0067) then
player:tradeComplete();
player:setVar("BetterPartOfValProg",4)
player:addKeyItem(XHIFHUT);
player:messageSpecial(KEYITEM_OBTAINED,XHIFHUT);
end
end;
| gpl-3.0 |
JoMiro/arcemu | src/scripts/lua/LuaBridge/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Terestian.lua | 30 | 1165 | function Terestian_Shadow_Bolt(Unit, event, miscunit, misc)
print "Terestian Shadow Bolt"
Unit:FullCastSpellOnTarget(36868,Unit:GetClosestPlayer())
Unit:SendChatMessage(11, 0, "I like shadow...")
end
function Terestian_Sacrifice(Unit, event, miscunit, misc)
print "Terestian Sacrifice"
Unit:FullCastSpellOnTarget(30115,Unit:GetRandomPlayer())
Unit:SendChatMessage(11, 0, "Sacrifice you for me...")
end
function Terestian_Kilrek(Unit, event, miscunit, misc)
if Unit:GetHealthPct(17229) < 0 and Didthat == 0 then
Unit:SpawnCreature(17229, -11236.9, -1695.81, 179.237, 0, 18, 96000000);
Unit:SendChatMessage(11, 0, "Come to help me Kilrek...")
Didthat = 1
else
end
end
function Terestian_Berserk(Unit, event, miscunit, misc)
print "Terestian Berserk"
Unit:FullCastSpell(38110)
Unit:SendChatMessage(11, 0, "Now, i'am verry mad...")
end
function Terestian(unit, event, miscunit, misc)
print "Terestian"
unit:RegisterEvent("Terestian_Shadow_Bolt",8000,0)
unit:RegisterEvent("Terestian_Sacrifice",33000,0)
unit:RegisterEvent("Terestian_Kilrek",45000,0)
unit:RegisterEvent("Terestian_Berserk",600000,0)
end
RegisterUnitEvent(15688,1,"Terestian") | agpl-3.0 |
lpiob/MTA-TokyoRPG | gamemode/RL_VEHICLE/vpanel_c.lua | 1 | 3614 | function convertNumber ( number )
local formatted = number
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if ( k==0 ) then
break
end
end
return formatted
end
local sw, sh = guiGetScreenSize()
addEventHandler("onClientRender",getRootElement(),function ()
if isPedInVehicle(localPlayer) then
local vehicle = getPedOccupiedVehicle(localPlayer)
dxDrawRectangle(0.779*sw, 0.278*sh, 0.170*sw, 0.0351*sh, tocolor(0, 0, 0, 226), true)
dxDrawText("Panel Pojazdu", 0.821*sw, 0.2851*sh, 0.900*sw, 0.3046*sh, tocolor(255, 255, 255, 255), 1.00, "default-bold", "left", "top", false, false, true, false, false)
dxDrawRectangle(0.779*sw, 0.313*sh, 0.170*sw, 0.2708*sh, tocolor(0, 0, 0, 160), true)
dxDrawRectangle(0.789*sw, 0.345*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawText("Pojazd: "..getVehicleName(vehicle), 0.789*sw, 0.345*sh, 0.9150*sw, 0.3671*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
dxDrawRectangle(0.779*sw, 0.4791*sh, 0.170*sw, 0.0078*sh, tocolor(0, 0, 0, 227), false)
dxDrawRectangle(0.789*sw, 0.3802*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawRectangle(0.789*sw, 0.4153*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawText("Stan: "..math.floor(health(vehicle)).."%", 0.789*sw, 0.380*sh, 0.9150*sw, 0.4024*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
dxDrawText("Paliwo: "..getElementData(vehicle,"vehicle:fuel").."%", 0.789*sw, 0.415*sh, 0.915*sw, 0.4375*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
dxDrawText("Informacje", 0.789*sw, 0.3216*sh, 0.9404*sw, 0.3398*sh, tocolor(255, 255, 255, 255), 1.00, "default", "center", "top", false, false, true, false, false)
dxDrawRectangle(0.789*sw, 0.519*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawRectangle(0.789*sw, 0.5481*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawText("Silnik: "..engine(vehicle), 0.789*sw, 0.5195*sh, 0.9150*sw, 0.40625*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
dxDrawText("Światła: "..lights(vehicle), 0.789*sw, 0.5481*sh, 0.9150*sw, 0.5703*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
dxDrawText("Funkcje", 0.789*sw, 0.492*sh, 0.9404*sw, 0.5104*sh, tocolor(255, 255, 255, 255), 1.00, "default", "center", "top", false, false, true, false, false)
dxDrawRectangle(0.789*sw, 0.450*sh, 0.151*sw, 0.022*sh, tocolor(0, 0, 0, 172), false)
dxDrawText("Przebieg: "..przebieg(vehicle), 0.789*sw, 0.4505*sh, 0.9150*sw, 0.4726*sh, tocolor(255, 255, 255, 255), 1.00, "default", "left", "top", false, false, true, false, false)
end
end)
function lights(vehicle)
if ( getVehicleOverrideLights(vehicle)==0 or getVehicleOverrideLights(vehicle)== 1 ) then
return "zgaszone"
else if getVehicleOverrideLights(vehicle)==2 then
return "zapalone"
end
end
end
function engine(vehicle)
if getVehicleEngineState(vehicle)== true then
return "zapalony"
else
return "zgaszony"
end
end
function health(vehicle)
local hp = getElementHealth(vehicle)
return hp / 10
end
function przebieg(vehicle)
local number = math.floor(getElementData(vehicle,"vehicle:travel"))
if number > 1000 then
return convertNumber(math.floor(number / 1000)).." Kilometry."
else
return math.floor(number).." Metry."
end
end
| gpl-2.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-openvpn/luasrc/model/cbi/openvpn-basic.lua | 10 | 3325 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: openvpn-basic.lua 7612 2011-10-06 22:37:27Z soma $
]]--
require("luci.ip")
require("luci.model.uci")
local basicParams = {
--
-- Widget, Name, Default(s), Description
--
{ ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") },
{ Value, "nice",0, translate("Change process priority") },
{ Value,"port",1194, translate("TCP/UDP port # for both local and remote") },
{ ListValue,"dev_type",{ "tun", "tap" }, translate("Type of used device") },
{ Flag,"tun_ipv6",0, translate("Make tun device IPv6 capable") },
{ Value,"ifconfig","10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") },
{ Value,"server","10.200.200.0 255.255.255.0", translate("Configure server mode") },
{ Value,"server_bridge","192.168.1.1 255.255.255.0 192.168.1.128 192.168.1.254", translate("Configure server bridge") },
{ Flag,"nobind",0, translate("Do not bind to local address and port") },
{ Flag,"comp_lzo",0, translate("Use fast LZO compression") },
{ Value,"keepalive","10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") },
{ ListValue,"proto",{ "udp", "tcp" }, translate("Use protocol") },
{ Flag,"client",0, translate("Configure client mode") },
{ Flag,"client_to_client",0, translate("Allow client-to-client traffic") },
{ DynamicList,"remote","vpnserver.example.org", translate("Remote host name or ip address") },
{ FileUpload,"secret","/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") },
{ FileUpload,"pkcs12","/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") },
{ FileUpload,"ca","/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") },
{ FileUpload,"dh","/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") },
{ FileUpload,"cert","/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") },
{ FileUpload,"key","/etc/easy-rsa/keys/some-client.key", translate("Local private key") },
}
local m = Map("openvpn")
local p = m:section( SimpleSection )
p.template = "openvpn/pageswitch"
p.mode = "basic"
p.instance = arg[1]
local s = m:section( NamedSection, arg[1], "openvpn" )
for _, option in ipairs(basicParams) do
local o = s:option(
option[1], option[2],
option[2], option[4]
)
o.optional = true
if option[1] == DummyValue then
o.value = option[3]
else
if option[1] == DynamicList then
o.cast = nil
function o.cfgvalue(...)
local val = AbstractValue.cfgvalue(...)
return ( val and type(val) ~= "table" ) and { val } or val
end
end
if type(option[3]) == "table" then
if o.optional then o:value("", "-- remove --") end
for _, v in ipairs(option[3]) do
v = tostring(v)
o:value(v)
end
o.default = tostring(option[3][1])
else
o.default = tostring(option[3])
end
end
for i=5,#option do
if type(option[i]) == "table" then
o:depends(option[i])
end
end
end
return m
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_ir9.lua | 17 | 1491 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: _ir9 (Iron Gate)
-- @pos 70 -1.5 140 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1660,1) and trade:getItemCount() == 1) then -- Bronze Key
player:tradeComplete();
npc:openDoor(15);
elseif (trade:hasItemQty(1022,1) and trade:getItemCount() == 1 and player:getMainJob() == 6) then -- thief's tool
player:tradeComplete();
npc:openDoor(15);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getXPos() >= 70) then
npc:openDoor(15); -- Retail timed
else
player:messageSpecial(DOOR_LOCKED,1660);
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 |
gheinrich/lua-pb | pb/proto/scanner.lua | 4 | 4555 | -- Copyright (c) 2010-2011 by Robert G. Jakabosky <bobby@neoawareness.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local _G = _G
local upper = string.upper
local mod_path = string.match(...,".*%.") or ''
local lp = require"lpeg"
local util = require(mod_path .. 'util')
local P=lp.P
local S=lp.S
local R=lp.R
local B=lp.B
local C=lp.C
local Cf=lp.Cf
local Cc=lp.Cc
module(...)
-------------------------------------------------------------------------------
------------------------- Basic Patterns
-------------------------------------------------------------------------------
-- numbers
local num_sign = (S'+-')
local digit = R'09'
local hexLit = P"0" * S"xX" * (R('09','af','AF'))^1
local octLit = P"0" * (R'07')^1
local floatLit = (digit^1 * ((P".")^-1 * digit^0)^-1 * (S'eE' * num_sign^-1 * digit^1)^-1)
local decLit = digit^1
local sdecLit = (P"-")^-1 * decLit
-- alphanumeric
local AZ = R('az','AZ')
local AlphaNum = AZ + R('09')
local identChar = AlphaNum + P"_"
local not_identChar = -identChar
local ident = (AZ + P"_") * (identChar)^0
local quote = P'"'
-------------------------------------------------------------------------------
------------------------- Util. functions.
-------------------------------------------------------------------------------
function lines(subject)
local _, num = subject:gsub('\n','')
return num + 1
end
function error(msg)
return function (subject, i)
local line = lines(subject:sub(1,i))
_G.error('Lexical error in line '..line..', near "'
.. util.show_text(subject:sub(i-10,i)).. '": ' .. msg, 0)
end
end
local function literals(tab, term)
local ret = P(false)
for i=1,#tab do
-- remove literal from list.
local lit = tab[i]
tab[i] = nil
-- make literal pattern
local pat = P(lit)
-- add terminal pattern
if term then
pat = pat * term
end
-- map LITERAL -> pattern(literal)
tab[upper(lit)] = pat
-- combind all literals into one pattern.
ret = pat + ret
end
return ret
end
-------------------------------------------------------------------------------
------------------------- Tokens
-------------------------------------------------------------------------------
keywords = {
-- package
"package", "import",
-- main types
"message", "extend", "enum",
"option",
-- field modifiers
"required", "optional", "repeated",
-- message extensions
"extensions", "to", "max",
-- message groups
"group",
-- RPC
"service",
"rpc", "returns",
-- buildin types
"double", "float",
"int32", "int64",
"uint32", "uint64",
"sint32", "sint64",
"fixed32", "fixed64",
"sfixed32", "sfixed64",
"bool",
"string", "bytes",
-- booleans
"true", "false",
}
KEYWORD = literals(keywords, not_identChar)
symbols = {
"=", ";",
".", ",",
"{", "}",
"(", ")",
"[", "]",
}
SYMBOL = literals(symbols)
INTEGER = hexLit + octLit + decLit
SINTEGER = hexLit + octLit + sdecLit
NUMERIC = hexLit + octLit + floatLit + decLit
SNUMERIC = hexLit + octLit + floatLit + sdecLit
IDENTIFIER = ident
STRING = quote * ((1 - S'"\n\r\\') + (P'\\' * 1))^0 * (quote + error"unfinished string")
COMMENT = (P"//" * (1 - P"\n")^0) + (P"/*" * (1 - P"*/")^0 * P"*/")
-------------------------------------------------------------------------------
------------------------- Other patterns
-------------------------------------------------------------------------------
SPACE = S' \t\n\r'
IGNORED = (SPACE + COMMENT)^0
TOKEN = IDENTIFIER + KEYWORD + SYMBOL + SNUMERIC + STRING
ANY = TOKEN + COMMENT + SPACE
BOF = P(function(s,i) return (i==1) and i end)
EOF = P(-1)
| mit |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Peritrage.lua | 36 | 1558 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Peritrage
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PERITRAGE_SHOP_DIALOG);
stock = {
0x4100, 284,3, --Bronze Axe
0x4101, 1435,3, --Brass Axe
0x4140, 604,3, --Butterfly Axe
0x4141, 4095,3, --Greataxe
0x4051, 147,3, --Bronze Knife
0x4052, 2182,3, --Knife
0x4040, 140,3, --Bronze Dagger
0x4041, 837,3, --Brass Dagger
0x4042, 1827,3 --Dagger
}
showNationShop(player, BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s7.lua | 17 | 1273 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -259 0 745 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-260);
local difZ = player:getZPos()-(754);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
birkett/MCServer | Server/Plugins/APIDump/Hooks/OnPlayerPlacedBlock.lua | 36 | 1637 | return
{
HOOK_PLAYER_PLACED_BLOCK =
{
CalledWhen = "After a player has placed a block. Notification only.",
DefaultFnName = "OnPlayerPlacedBlock", -- also used as pagename
Desc = [[
This hook is called after a {{cPlayer|player}} has placed a block in the {{cWorld|world}}. The block
is already added to the world and the corresponding item removed from player's
{{cInventory|inventory}}.</p>
<p>
Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.</p>
<p>
See also the {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook for a similar hook called
before the placement.</p>
<p>
If the client action results in multiple blocks being placed (such as a bed or a door), each separate
block is reported through this hook. All the blocks are already present in the world before the first
instance of this hook is called.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who placed the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
},
Returns = [[
If this function returns false or no value, Cuberite calls other plugins with the same event. If
this function returns true, no other plugin is called for this event.
]],
}, -- HOOK_PLAYER_PLACED_BLOCK
}
| apache-2.0 |
jshackley/darkstar | scripts/zones/Chateau_dOraguille/npcs/Nachou.lua | 38 | 1046 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Nachou
-- Type: Standard NPC
-- @zone: 233
-- @pos -39.965 -3.999 34.292
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x020b);
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 |
jshackley/darkstar | scripts/zones/RaKaznar_Inner_Court/npcs/HomePoint#1.lua | 4 | 1202 | -----------------------------------
-- Area: RaKaznar_Inner_Court
-- NPC: HomePoint#1
-- @pos
-----------------------------------
package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/RaKaznar_Inner_Court/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 116);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s5.lua | 17 | 1275 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -779 0 -454 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-780);
local difZ = player:getZPos()-(-446);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Port_Bastok/npcs/Raifa.lua | 38 | 1026 | -----------------------------------
-- Area: Port Bastok
-- NPC: Raifa
-- Type: Quest Giver
-- @zone: 236
-- @pos -166.416 -8.48 7.153
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0116);
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 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Anillah.lua | 53 | 1829 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Anillah
-- Type: Clothcraft Image Support
-- @pos -34.800 -2.25 -119.950 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,3);
local SkillCap = getCraftSkillCap(player,SKILL_CLOTHCRAFT);
local SkillLevel = player:getSkillLevel(SKILL_CLOTHCRAFT);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then
player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),7108,0,0);
end
else
player:startEvent(0x271F); -- Standard Dialogue
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 == 0x271F and option == 1) then
player:messageSpecial(IMAGE_SUPPORT,0,4,2);
player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/runes/handlers.lua | 3 | 3652 | -- Use handlers for runes
-- Every handler must receive as arguments the default callback arguments and
-- as first argument the power level of the rune as a string which can be :
-- `minor` : Low level
-- `medium` : Medium level
-- `major` : High level
-- First, the functions
projection = function(runelevel, itemstack, user, pointed_thing)
if pointed_thing.type == "object" then
local dir = vector.direction(user:getpos(),pointed_thing.ref:getpos())
local v = pointed_thing.ref:getvelocity() or {x=0,y=0,z=0}
local ykb = 10
if v.y ~= 0 then ykb = 0 end
pointed_thing.ref:setvelocity({x=dir.x*50,y=ykb,z=dir.z*50})
end
end
damage_around = function(runelevel, itemstack, user, pointed_thing)
for name,entity in pairs(minetest.get_objects_inside_radius(user:getpos(),10)) do
if true and (entity:is_player() and entity:get_player_name() ~= user:get_player_name()) then
entity:set_hp(1)
end
end
end
earthquake = function(runelevel, itemstack, user, pointed_thing)
for name,entity in pairs(minetest.get_objects_inside_radius(user:getpos(),10)) do
local v = entity:get_velocity() or {x=0,y=0,z=0}
entity:set_velocity({x=v.x, y=v.y+50, z=v.z})
end
end
add_owner = function(runelevel, pos, placer, itemstack, pointed_thing)
if placer and placer:is_player() then
local meta = minetest.get_meta(pos)
meta:set_string("owner",placer:get_player_name())
end
end
is_owner_online = function(runelevel, pos)
local meta = minetest.get_meta(pos)
if meta:get_string("owner") ~= nil then
return minetest.get_player_by_name(meta:get_string("owner")) ~= nil
else
return false
end
end
is_owner = function(runelevel, pos, player)
local meta = minetest.get_meta(pos)
if meta:get_string("owner") ~= nil and player:get_player_name() then
return meta:get_string("owner") == player:get_player_name()
else
return false
end
end
go_to_me = function(runelevel, pos, node, digger)
if digger and is_owner_online(pos) and not (minetest.get_meta(pos):get_string("owner") == digger:get_player_name()) then
digger:setpos(minetest.get_player_by_name(minetest.get_meta(pos):get_string("owner")):getpos())
mana.subtract(minetest.get_meta(pos):get_string("owner"), 5)
else
mana.add(digger:get_player_name(),50)
end
end
set_manamax = function(runelevel, itemstack, user, pointed_thing)
if user and user:is_player() then
mana.set(user:get_player_name(),mana.getmax(user:get_player_name()))
if not minetest.get_player_privs(user:get_player_name()).server then
-- Violent reaction if not admin
user:set_hp(1)
user:set_breath(1)
local userpos = user:get_pos()
local useritem = user:get_wielded_item()
user:setpos({x=userpos.x+math.random(-50,50),y = userpos.y + math.random(1,20),z = userpos.z + math.random(-50,50)})
end
end
end
set_manamax = function(level, itemstack, user, pointed_thing)
if user and user:is_player() then
mana.set(user:get_player_name(),mana.getmax(user:get_player_name()))
if not minetest.get_player_privs(user:get_player_name()).server then
-- Violent reaction if not admin
user:set_hp(1)
user:set_breath(1)
local userpos = user:get_pos()
local useritem = user:get_wielded_item()
user:setpos({x=userpos.x+math.random(-50,50),y = userpos.y + math.random(1,20),z = userpos.z + math.random(-50,50)})
end
end
end
-- Then, connect
runes.functions.connect("project","use",projection)
runes.functions.connect("damager","use",damage_around)
runes.functions.connect("earthquake","use",earthquake)
runes.functions.connect("gotome","punch",go_to_me)
runes.functions.connect("gotome","can_dig",is_owner)
runes.functions.connect("megamana","use",set_manamax)
| unlicense |
jshackley/darkstar | scripts/zones/QuBia_Arena/mobs/Vangknok_of_Clan_Death.lua | 8 | 2652 | -----------------------------------
-- Area: QuBia_Arena
-- Mission 9-2 SANDO
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
local mobs= {{17621017,17621018,17621019,17621020,17621021,17621022,17621023,17621024,17621025,17621026,17621027},{17621031,17621032,17621033,17621034,17621035,17621036,17621037,17621038,17621039,17621040,17621041},{17621031,17621046,17621047,17621048,17621049,17621050,17621051,17621052,17621053,17621054,17621055}};
local inst=ally:getBattlefield():getBattlefieldNumber();
local victory = true
for i,v in ipairs(mobs[inst]) do
local action = GetMobAction(v);
printf("action %u",action);
if not(action == 0 or (action >=21 and action <=23)) then
victory = false
end
end
if victory == true then
ally:startEvent(0x7d04,0,0,4);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("finishCSID: %u",csid);
printf("RESULT: %u",option);
if (csid == 0x7d04) then
if (player:getBattlefield():getBattlefieldNumber() == 1) then
SpawnMob(17621014);
SpawnMob(17621015);
SpawnMob(17621016);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-403,-201,413,58);
trion:spawn();
player:setPos(-400,-201,419,61);
elseif (player:getBattlefield():getBattlefieldNumber() == 2) then
SpawnMob(17621028);
SpawnMob(17621029);
SpawnMob(17621030);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-3,-1,4,61);
trion:spawn();
player:setPos(0,-1,10,61);
elseif (player:getBattlefield():getBattlefieldNumber() == 3) then
SpawnMob(17621042);
SpawnMob(17621043);
SpawnMob(17621044);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(397,198,-395,64);
trion:spawn();
player:setPos(399,198,-381,57);
end
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/tachi_hobaku.lua | 18 | 1659 | -----------------------------------
-- Tachi Hobaku
-- Great Katana weapon skill
-- Skill Level: 30
-- Stuns enemy. Chance of stun varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Snow Gorget.
-- Aligned with the Snow Belt.
-- Element: None
-- Modifiers: STR:60%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.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.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;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
local chance = player:getTP()-100 > math.random()*150;
if (damage > 0 and chance) then
if (target:hasStatusEffect(EFFECT_STUN) == false) then
target:addStatusEffect(EFFECT_STUN, 1, 0, 4);
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
JoMiro/arcemu | src/scripts/lua/LuaBridge/0Misc/0LCF_Includes/LCF_Extra.lua | 13 | 5292 | --[[
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2010 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*]]
assert( include("LCF.lua") )
LCF.zone_hooks = {}
LCF.areatrigger_hooks = {}
LCF.call_backs = {}
function LCF:HandleOnZone(event,player,zone_id)
local zone_key = "zone "..tostring(zone_id)
local zone_struct = self.zone_hooks[zone_key]
if(type(zone_struct) == "table") then
for _,v in pairs(zone_struct) do
if(type(v) == "function") then
--pcall(v,event,player,zone_id)
v(event,player,zone_id)
end
end
end
end
function LCF:HandleOnAreaTrigger(event,player,area_trig)
--player:SendAreaTriggerMessage("[AREA TRIGGER] "..area_trig)
local key = "area "..tostring(area_trig)
local struct = self.areatrigger_hooks[key]
if(type(struct) == "table") then
for _,v in pairs(struct) do
if(type(v) == "function") then
--pcall(v,event,player,area_trig)
v(event,player,area_trig)
end
end
end
end
function LCF:RegisterZoneHook(zone_id, func)
assert(zone_id and func,"Failed, expected valid values got ->"..tostring(zone_id).." : "..tostring(func))
if(type(func) ~= "function") then error("Failed to register, expected valid function got->"..tostring(func)) end
local zone_key = "zone "..tostring(zone_id)
if(type(self.zone_hooks[zone_key]) ~= "table") then
self.zone_hooks[zone_key] = {}
end
local fstr = tostring(func)
--first, try to find it.
for _,v in pairs(self.zone_hooks[zone_key]) do
if(tostring(v) == fstr) then
return
end
end
table.insert(self.zone_hooks[zone_key],func)
end
function LCF:RemoveZoneHook(zone_id, func)
local zone_key = "zone "..tostring(zone_id)
local zone_struct = self.zone_hooks[zone_key]
local fstr = tostring(func)
if(type(zone_struct) == "table") then
for k,v in pairs(zone_struct) do
if(tostring(v) == fstr) then
table.remove(zone_struct,k)
break
end
end
end
end
function LCF:RegisterAreaTrigger(area_trig, func)
assert(area_trig and func,"Failed, expected valid values got ->"..tostring(area_trig).." : "..tostring(func))
if(type(area_trig) ~= "number") then error("Failed to register, expected number value, got ->"..tostring(area_trig)) end
if(type(func) ~= "function") then error("Failed to register, expected valid function got->"..tostring(func)) end
local key = "area "..tostring(area_trig)
local fstr = tostring(func)
if(type(self.areatrigger_hooks[key]) ~= "table") then
self.areatrigger_hooks[key] = {}
end
for _,v in pairs(self.areatrigger_hooks[key]) do
if(type(v) == fstr) then
return
end
end
table.insert(self.areatrigger_hooks[key],func)
end
function LCF:RemoveAreaTrigger(area_trig,func)
local key = "area "..tostring(area_trig)
local struct = self.areatrigger_hooks[key]
local fstr = tostring(func)
if(type(struct) == "table") then
for k,v in pairs(struct) do
if(type(v) == fstr) then
table.remove(struct,k)
break;
end
end
end
end
function LCF:RegisterLuaEvent(evt_typ,func,delay,repeats,...)
if(type(func) ~= "function") then error("Invalid argument #1, expected function got ->"..type(func)) end
if(type(delay) ~= "number") then error("Invalid argument #2, expected number got ->"..type(delay)) end
if(type(repeats) ~= "number") then error("Invalid argument #3, expected number got->"..type(repeats)) end
assert(type(arg) == "table","Internal error, arg is not a table.")
if(delay <= 0) then error("Invalid argument #2, delay must be greater than 0.") end
local struct = {evt_typ,{func,delay,delay,repeats,arg} }
table.insert(self.call_backs,struct)
end
function LCF:RemoveLuaEvent(evt_typ,func)
for k,v in ipairs(self.call_backs) do
if(v[1] == evt_typ) then
if(func ~= nil) then
local struct = v[2]
local fstr = tostring(func)
if(tostring(struct[1]) == fstr) then
table.remove(self.call_backs,k)
end
else
table.remove(self.call_backs,k)
end
end
end
end
function LCF:UpdateCallBacks(...)
for k,v in pairs(self.call_backs) do
local struct = v[2]
struct[2] = (struct[2] - 100)
if(struct[2] <= 0) then
struct[1](unpack(struct[5]))
struct[2] = struct[3]
if(struct[4] ~= 0) then
struct[4] = struct[4] - 1
if(struct[4] == 0) then
table.remove(self.call_backs,k)
end
end
end
end
end
function LCF:BindMethod(method,method_table)
return function(...) return method(method_table,unpack(arg)) end
end
RegisterServerHook(15,LCF:BindMethod(LCF.HandleOnZone,LCF))
RegisterServerHook(26,LCF:BindMethod(LCF.HandleOnAreaTrigger,LCF))
--RegisterTimedEvent("LCF:UpdateCallBacks",100,0)
--CreateLuaEvent(LCF:BindMethod(LCF.UpdateCallBacks,LCF),100,0) | agpl-3.0 |
jshackley/darkstar | scripts/zones/Metalworks/npcs/Moyoyo.lua | 38 | 1034 | -----------------------------------
-- Area: Metalworks
-- NPC: Moyoyo
-- Type: Standard NPC
-- @zone: 237
-- @pos 19.508 -17 26.870
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00fc);
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 |
SpRoXx/GTW-RPG | [resources]/GTWcivilians/civ_c.lua | 1 | 13709 | --[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- GUI components
local work_window = nil
local btn_accept = nil
local btn_cancel = nil
local lbl_info = nil
local lst_skins = nil
local cooldown = nil
local cooldown2 = nil
-- Global data
local dummyped = nil
local playerSkinID = 0
local playerCurrentSkin = 0
--[[ Create the job window ]]--
addEventHandler("onClientResourceStart", resourceRoot,
function()
-- Adding the gui
local guiX,guiY = guiGetScreenSize()
work_window = guiCreateWindow(0, (guiY-350)/2, 372, 350, "Civilians", false)
guiSetVisible(work_window, false)
-- Tab panel
tab_panel = guiCreateTabPanel(0, 30, 372, 276, false, work_window)
tab_info = guiCreateTab("Information", tab_panel)
tab_skin = guiCreateTab("Select skin", tab_panel)
tab_weapons = guiCreateTab("Rent weapons/tools", tab_panel)
-- Button accept
btn_accept = guiCreateButton(10, 310, 110, 36, "Accept", false, work_window)
guiSetProperty(btn_accept, "NormalTextColour", "FF00FF00")
addEventHandler("onClientGUIClick", btn_accept, accept_work, false)
exports.GTWgui:setDefaultFont(btn_accept, 10)
-- Button close
btn_cancel = guiCreateButton(252, 310, 110, 36, "Cancel", false, work_window)
addEventHandler("onClientGUIClick", btn_cancel, close_guibutton, false)
exports.GTWgui:setDefaultFont(btn_cancel, 10)
-- Memo with info
lbl_info = guiCreateMemo(0, 0, 1, 1, "Loading info...", true, tab_info)
guiMemoSetReadOnly( lbl_info, true )
exports.GTWgui:setDefaultFont(lbl_info, 10)
-- Skin selection list
lst_skins = guiCreateGridList( 0, 0, 1, 1, true, tab_skin )
guiGridListSetSelectionMode( lst_skins, 2 )
guiGridListAddColumn( lst_skins, "Skin name", 0.65 )
guiGridListAddColumn( lst_skins, "ID", 0.15 )
exports.GTWgui:setDefaultFont(lst_skins, 10)
guiGridListSetSelectionMode(lst_skins, 0)
guiGridListSetSortingEnabled(lst_skins, false)
-- Weapons and tools selection list
lst_weapons = guiCreateGridList( 0, 0, 1, 1, true, tab_weapons )
guiGridListSetSelectionMode( lst_weapons, 2 )
guiGridListAddColumn( lst_weapons, "Weapon name", 0.5 )
guiGridListAddColumn( lst_weapons, "Ammo", 0.15 )
guiGridListAddColumn( lst_weapons, "Price", 0.15 )
guiGridListAddColumn( lst_weapons, "ID", 0.10 )
exports.GTWgui:setDefaultFont(lst_weapons, 10)
guiGridListSetSelectionMode(lst_weapons, 0)
guiGridListSetSortingEnabled(lst_weapons, false)
-- Add all markers created by this system if any
addMarkersAndClearTable()
end)
function addMarkersAndClearTable()
-- Add job markers to the map
for k, v in pairs(markers) do
-- Unpack data
local ID, inter,dim, x,y,z, j_type = unpack(v)
if not ID or not inter or not dim or not x or not y or not z or not j_type then return end
-- Update color profiles
local red,green,blue = 255,150,0
if j_type == "government" then
red,green,blue = 110,110,110
elseif j_type == "emergency" then
red,green,blue = 0,150,255
end
-- Create the marker
local mark = createMarker(x, y, z-1, "cylinder", 2.0, red, green, blue, 70)
if inter == 0 then createBlipAttachedTo( mark, 56, 2, 0, 0, 0, 0, 0, 180) end
setElementInterior(mark, inter)
setElementDimension(mark, dim)
addEventHandler("onClientMarkerHit", mark, showGUI)
addEventHandler("onClientMarkerLeave", mark, close_gui)
setElementData( mark, "jobID", ID )
end
-- Clear the table
markers = { }
end
-- Check if a refresh is needed
setTimer(addMarkersAndClearTable, 5000, 0)
--[[ Shows the gui on marker hit and edit it's variables ]]--
function showGUI( hitElement, matchingdimension, jobID )
if not isTimer(cooldown) and hitElement and isElement(hitElement) and getElementType(hitElement) == "player"
and not getPedOccupiedVehicle(hitElement) and getElementData(hitElement, "Jailed") ~= "Yes" and hitElement == localPlayer
and matchingdimension then
-- Get job id from marker
local ID = ""
if source then ID = getElementData( source, "jobID" ) else
ID = jobID end
local team, max_wl, description, skins, skin_names, work_tools = unpack(work_items[ID])
-- Check group membership
if restricted_jobs[ID] then
if restricted_jobs[ID] ~= getElementData(localPlayer, "Group") and getPlayerTeam(localPlayer) ~= getTeamFromName("Staff") then
exports.GTWtopbar:dm( ID..": This job is restricted to: "..restricted_jobs[ID], 255, 100, 0 )
return
end
end
-- Check wanted level
if getPlayerWantedLevel() > max_wl then
exports.GTWtopbar:dm( ID..": Go away, we don't hire criminals!", 255, 0, 0 )
return
end
if getElementData(localPlayer, "Occupation") == ID then
guiSetEnabled(tab_info, false)
guiSetEnabled(tab_skin, false)
guiSetSelectedTab(tab_panel, tab_weapons)
guiSetVisible(btn_accept, false)
guiSetText(btn_cancel, "OK")
else
guiSetEnabled(tab_info, true)
guiSetEnabled(tab_skin, true)
guiSetSelectedTab(tab_panel, tab_info)
guiSetVisible(btn_accept, true)
guiSetText(btn_cancel, "Cancel")
end
-- Freeze the player
setElementFrozen(hitElement, true)
-- Move to skin selection area
g_px,g_py,g_pz = getElementPosition(localPlayer)
g_prx,g_pry,g_prz = getElementRotation(localPlayer)
g_pdim = getElementDimension(localPlayer)
g_pint = getElementInterior(localPlayer)
fadeCamera(false)
dummyped = createPed(0, -1618.2958984375, 1400.9755859375, 7.1753273010254, 180)
-- Fade and move the camera
local new_dim = math.random(100,200)
setTimer(fadeCamera, 1000, 1, true)
setTimer(setElementDimension, 1000, 1, localPlayer, new_dim)
setTimer(setElementInterior, 1000, 1, localPlayer, 0)
setTimer(setElementDimension, 1000, 1, dummyped, new_dim)
setTimer(setElementInterior, 1000, 1, dummyped, 0)
setTimer(setCameraMatrix, 1000, 1, -1618.2958984375, 1398, 7.1753273010254, -1618.2958984375, 1400.9755859375, 7.1753273010254, 5, 100)
-- Set GUI information and save skin information
guiSetText(lbl_info, ID.."\n"..description)
setElementData(localPlayer, "jobID", ID)
setElementData(localPlayer, "GTWcivilians.skins.current", getElementModel(localPlayer))
playerCurrentSkin = getElementModel(localPlayer)
-- Clear skins list
guiGridListClear( lst_skins )
-- Add category
local tmp_row_cat = guiGridListAddRow( lst_skins )
guiGridListSetItemText( lst_skins, tmp_row_cat, 1,ID.." skins",true,false)
-- Add available skins
for k=1, #skins do
if skins[k] == -1 then
-- Alias for default skin
local tmp_row = guiGridListAddRow( lst_skins )
guiGridListSetItemText( lst_skins, tmp_row, 1,"Default",false,false)
elseif skins[k] > -1 then
-- All other available skins
local tmp_row = guiGridListAddRow( lst_skins )
guiGridListSetItemText( lst_skins,tmp_row,2,skins[k],false,false)
guiGridListSetItemText( lst_skins,tmp_row,1,skin_names[k],false,false)
end
end
-- Clear weapons list
guiGridListClear( lst_weapons )
-- Add available weapons
for i=1, #work_tools do
local tmp_row = guiGridListAddRow( lst_weapons )
local wep_id,ammo,price,name = unpack(work_tools[i])
guiGridListSetItemText(lst_weapons,tmp_row,1, name, false,false)
guiGridListSetItemText(lst_weapons,tmp_row,2, ammo, false,false)
guiGridListSetItemText(lst_weapons,tmp_row,3, price, false,false)
guiGridListSetItemText(lst_weapons,tmp_row,4, wep_id, false,false)
end
-- Select default item
guiGridListSetSelectedItem( lst_skins, 0, 0 )
row,col = 0,0 -- Default
setTimer(function()
if skins[1] > -1 then
setElementModel( dummyped, skins[1] )
playerSkinID = skins[1]
else
local currSkinID = tonumber(getElementData(localPlayer, "clothes.boughtSkin")) or 0
setElementModel( dummyped, currSkinID )
playerSkinID = currSkinID
end
end, 1000, 1)
-- On skin change
addEventHandler("onClientGUIClick",lst_skins,
function()
row,col = guiGridListGetSelectedItem( lst_skins )
if row and col and row > 0 then
playerSkinID = (skins[row] or 0)
if playerSkinID > -1 then
setElementModel( dummyped, playerSkinID )
elseif playerSkinID == -1 then
local currSkinID = tonumber(getElementData(localPlayer, "clothes.boughtSkin")) or 0
setElementModel( dummyped, currSkinID )
end
end
end)
addEventHandler( "onClientGUIDoubleClick", lst_weapons, function( )
local r,c = guiGridListGetSelectedItem(lst_weapons)
local name = guiGridListGetItemText(lst_weapons, r,1)
local ammo = guiGridListGetItemText(lst_weapons, r,2)
local price = guiGridListGetItemText(lst_weapons, r,3)
local weapon_id = guiGridListGetItemText(lst_weapons, r,4)
if not isTimer(cooldown2) and r > -1 and c > -1 then
triggerServerEvent("GTWcivilians.buyTools", localPlayer, name, ammo, price, weapon_id)
cooldown2 = setTimer(function() end, 200, 1)
end
end)
-- Showing the gui
setTimer(guiSetVisible, 1000, 1, work_window, true)
setTimer(guiSetInputEnabled, 1000, 1, true)
setTimer(showCursor, 1000, 1, true)
end
end
function staffWork(cmdName, ID)
-- Configuration
-- Setup by name
if cmdName ~= "gowork" then
if cmdName == "gobusdriver" then
ID = "Bus Driver"
elseif cmdName == "gotrain" then
ID = "Train Driver"
elseif cmdName == "gotaxi" then
ID = "Taxi Driver"
elseif cmdName == "gotrucker" then
ID = "Trucker"
elseif cmdName == "gopilot" then
ID = "Pilot"
elseif cmdName == "gomechanic" then
ID = "Mechanic"
elseif cmdName == "gofisher" then
ID = "Fisher"
elseif cmdName == "gofarmer" then
ID = "Farmer"
elseif cmdName == "gotram" then
ID = "Tram Driver"
elseif cmdName == "gofireman" then
ID = "Fireman"
elseif cmdName == "gomedic" then
ID = "Paramedic"
elseif cmdName == "goironminer" then
ID = "Iron miner"
elseif cmdName == "golaw" then
ID = "Police Officer"
elseif cmdName == "sapd" then
ID = "SAPD Officer"
elseif cmdName == "swat" then
ID = "SWAT Officer"
elseif cmdName == "fbi" then
ID = "FBI agent"
elseif cmdName == "army" then
ID = "Armed Forces"
end
end
-- Check if a user is in the staff team, if so, allow access
local is_staff = exports.GTWstaff:isStaff(localPlayer)
if restricted_jobs[ID] and (not is_staff or restricted_jobs[ID] ~= getElementData(localPlayer, "Group")) then
exports.GTWtopbar:dm( ID..": Only staff and official groups can use this command!", 255, 100, 0 )
return
end
if ID then
showGUI(localPlayer, true, ID)
end
end
addCommandHandler( "gowork", staffWork )
addCommandHandler( "gobusdriver", staffWork )
addCommandHandler( "gotrucker", staffWork )
addCommandHandler( "gotaxi", staffWork )
addCommandHandler( "gotrain", staffWork )
addCommandHandler( "gopilot", staffWork )
addCommandHandler( "gofisher", staffWork )
addCommandHandler( "gofarmer", staffWork )
addCommandHandler( "gomechanic", staffWork )
addCommandHandler( "gotram", staffWork )
addCommandHandler( "gofireman", staffWork )
addCommandHandler( "gomedic", staffWork )
addCommandHandler( "goironminer", staffWork )
addCommandHandler( "golaw", staffWork )
-- Group commands
addCommandHandler( "fbi", staffWork )
addCommandHandler( "swat", staffWork )
addCommandHandler( "sapd", staffWork )
addCommandHandler( "army", staffWork )
--[[ Closes the GUI on marker leave ]]--
function close_gui( leaveElement, matchingdimension )
if ( leaveElement and isElement(leaveElement) and getElementType(leaveElement) == "player"
and not getPedOccupiedVehicle(leaveElement) and leaveElement == localPlayer
and matchingdimension ) then
end
end
--[[ When the user clicks on the Accept job button ]]--
function accept_work()
-- Trigger server event
local ID = getElementData( localPlayer, "jobID" )
if not playerSkinID then
playerSkinID = 0
end
-- Accept job
if ID then
triggerServerEvent( "GTWcivilians.accept", localPlayer, ID, playerSkinID )
end
-- Reset camera details
fadeCamera(false)
setTimer(reset_close_gui, 1000, 1)
cooldown = setTimer(function() end, 3000, 1)
-- Unfreeze player
setTimer(setElementFrozen, 2000, 1, localPlayer, false)
-- Closing the gui
guiSetVisible( work_window, false )
guiSetInputEnabled( false )
showCursor( false )
end
--[[ When the user clicks on the Close button ]]--
function close_guibutton()
-- Closing the gui
guiSetVisible( work_window, false )
guiSetInputEnabled( false )
showCursor( false )
-- Unfreeze player
setTimer(setElementFrozen, 2000, 1, localPlayer, false)
-- Reset camera details
fadeCamera(false)
setTimer(reset_close_gui, 1000, 1)
cooldown = setTimer(function() end, 3000, 1)
-- Reset Skin
--local skinID = getElementData(localPlayer, "GTWcivilians.skins.current") or 0
--setElementModel(localPlayer, skinID)
end
function reset_close_gui()
-- Fade and move the camera back to default
fadeCamera(true)
setElementDimension(localPlayer, g_pdim)
setElementInterior(localPlayer, g_pint)
setElementPosition(localPlayer, g_px,g_py,g_pz)
setElementRotation(localPlayer, g_prx,g_pry,g_prz)
destroyElement(dummyped)
setCameraTarget(localPlayer)
setElementFrozen(localPlayer, false)
end
| bsd-2-clause |
jshackley/darkstar | scripts/globals/items/berry_snowcone.lua | 39 | 1200 | -----------------------------------------
-- ID: 5710
-- Item: Berry Snowcone
-- Food Effect: 5 Min, All Races
-----------------------------------------
-- MP % 30 Cap 30
-- Intelligence 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5710);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 30);
target:addMod(MOD_FOOD_MP_CAP, 30);
target:addMod(MOD_INT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 30);
target:delMod(MOD_FOOD_MP_CAP, 30);
target:delMod(MOD_INT, 1);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Abdhaljs_Isle-Purgonorgo/Zone.lua | 34 | 1365 | -----------------------------------
--
-- Zone: Abdhaljs_Isle-Purgonorgo
--
-----------------------------------
package.loaded["scripts/zones/Abdhaljs_Isle-Purgonorgo/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Abdhaljs_Isle-Purgonorgo/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
player:addKeyItem(MAP_OF_ABDH_ISLE_PURGONORGO);
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(521.600,-3.000,563.000,64);
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 |
asmagill/hs._asm.luathread | luaskin/modules/timer/init.lua | 9 | 14969 | --- === hs.timer ===
---
--- Execute functions with various timing rules
local module = require("hs.timer.internal")
local log=require'hs.logger'.new('timer',3)
module.setLogLevel=log.setLogLevel
local type,ipairs,tonumber,floor,date=type,ipairs,tonumber,math.floor,os.date
-- private variables and methods -----------------------------------------
local TIME_PATTERNS={'-??:??:??-','-??:??--','??d??h---','-??h??m--','--??m??s-','??d----','-??h---','--??m--','---??s-','----????ms'}
-- ms unused, but it might be useful in the future
do
for i,s in ipairs(TIME_PATTERNS) do
TIME_PATTERNS[i]='^'..(s:gsub('%?%?%?%?','(%%d%%d?%%d?%%d?)'):gsub('%?%?','(%%d%%d?)'):gsub('%-','()'))..'$'
end
end
local function timeStringToSeconds(time)
if type(time)=='string' then
local d,h,m,s,ms
for _,pattern in ipairs(TIME_PATTERNS) do
d,h,m,s,ms=time:match(pattern) if d then break end
end
if not d then error('invalid time string '..time,3) end
if type(d)=='number' then d=0 end --remove "missing" captures
if type(h)=='number' then h=0 end
if type(m)=='number' then m=0 end
if type(s)=='number' then s=0 end
if type(ms)=='number' then ms=0 end
d=tonumber(d) h=tonumber(h) m=tonumber(m) s=tonumber(s) ms=tonumber(ms)
if h>=24 or m>=60 or s>=60 then error('invalid time string '..time,3) end
time=d*86400+h*3600+m*60+s+(ms/1000)
end
if type(time)~='number' or time<0 then error('invalid time',3) end
return time
end
-- Public interface ------------------------------------------------------
--- hs.timer.seconds(timeOrDuration) -> seconds
--- Function
--- Converts a string with a time of day or a duration into number of seconds
---
--- Parameters:
--- * timeOrDuration - a string that can have any of the following formats:
--- * "HH:MM:SS" or "HH:MM" - represents a time of day (24-hour clock), returns the number of seconds since midnight
--- * "DDdHHh", "HHhMMm", "MMmSSs", "DDd", "HHh", "MMm", "SSs", "NNNNms" - represents a duration in days, hours, minutes,
--- seconds and/or milliseconds
---
--- Returns:
--- * The number of seconds
function module.seconds(n) return timeStringToSeconds(n) end
--- hs.timer.minutes(n) -> seconds
--- Function
--- Converts minutes to seconds
---
--- Parameters:
--- * n - A number of minutes
---
--- Returns:
--- * The number of seconds in n minutes
function module.minutes(n) return 60 * n end
--- hs.timer.hours(n) -> seconds
--- Function
--- Converts hours to seconds
---
--- Parameters:
--- * n - A number of hours
---
--- Returns:
--- * The number of seconds in n hours
function module.hours(n) return 60 * 60 * n end
--- hs.timer.days(n) -> sec
--- Function
--- Converts days to seconds
---
--- Parameters:
--- * n - A number of days
---
--- Returns:
--- * The number of seconds in n days
function module.days(n) return 60 * 60 * 24 * n end
--- hs.timer.weeks(n) -> sec
--- Function
--- Converts weeks to seconds
---
--- Parameters:
--- * n - A number of weeks
---
--- Returns:
--- * The number of seconds in n weeks
function module.weeks(n) return 60 * 60 * 24 * 7 * n end
--- hs.timer.waitUntil(predicateFn, actionFn[, checkInterval]) -> timer
--- Constructor
--- Creates and starts a timer which will perform `actionFn` when `predicateFn` returns true. The timer is automatically stopped when `actionFn` is called.
---
--- Parameters:
--- * predicateFn - a function which determines when `actionFn` should be called. This function takes no arguments, but should return true when it is time to call `actionFn`.
--- * actionFn - a function which performs the desired action. This function may take a single argument, the timer itself.
--- * checkInterval - an optional parameter indicating how often to repeat the `predicateFn` check. Defaults to 1 second.
---
--- Returns:
--- * a timer object
---
--- Notes:
--- * The timer is stopped before `actionFn` is called, but the timer is passed as an argument to `actionFn` so that the actionFn may restart the timer to be called again the next time predicateFn returns true.
--- * See also `hs.timer.waitWhile`, which is essentially the opposite of this function
module.waitUntil = function(predicateFn, actionFn, checkInterval)
checkInterval = checkInterval or 1
local stopWatch
stopWatch = module.new(checkInterval, function()
if predicateFn() then
stopWatch:stop()
actionFn(stopWatch)
end
end):start()
return stopWatch
end
--- hs.timer.doUntil(predicateFn, actionFn[, checkInterval]) -> timer
--- Constructor
--- Creates and starts a timer which will perform `actionFn` every `checkinterval` seconds until `predicateFn` returns true. The timer is automatically stopped when `predicateFn` returns true.
---
--- Parameters:
--- * predicateFn - a function which determines when to stop calling `actionFn`. This function takes no arguments, but should return true when it is time to stop calling `actionFn`.
--- * actionFn - a function which performs the desired action. This function may take a single argument, the timer itself.
--- * checkInterval - an optional parameter indicating how often to repeat the `predicateFn` check. Defaults to 1 second.
---
--- Returns:
--- * a timer object
---
--- Notes:
--- * The timer is passed as an argument to `actionFn` so that it may stop the timer prematurely (i.e. before predicateFn returns true) if desired.
--- * See also `hs.timer.doWhile`, which is essentially the opposite of this function
module.doUntil = function(predicateFn, actionFn, checkInterval)
checkInterval = checkInterval or 1
local stopWatch
stopWatch = module.new(checkInterval, function()
if not predicateFn() then
actionFn(stopWatch)
else
stopWatch:stop()
end
end):start()
return stopWatch
end
--- hs.timer.doEvery(interval, fn) -> timer
--- Constructor
--- Repeats fn every interval seconds.
---
--- Parameters:
--- * interval - A number of seconds between triggers
--- * fn - A function to call every time the timer triggers
---
--- Returns:
--- * An `hs.timer` object
---
--- Notes:
--- * This function is a shorthand for `hs.timer.new(interval, fn):start()`
module.doEvery = function(...)
return module.new(...):start()
end
--- hs.timer.waitWhile(predicateFn, actionFn[, checkInterval]) -> timer
--- Constructor
--- Creates and starts a timer which will perform `actionFn` when `predicateFn` returns false. The timer is automatically stopped when `actionFn` is called.
---
--- Parameters:
--- * predicateFn - a function which determines when `actionFn` should be called. This function takes no arguments, but should return false when it is time to call `actionFn`.
--- * actionFn - a function which performs the desired action. This function may take a single argument, the timer itself.
--- * checkInterval - an optional parameter indicating how often to repeat the `predicateFn` check. Defaults to 1 second.
---
--- Returns:
--- * a timer object
---
--- Notes:
--- * The timer is stopped before `actionFn` is called, but the timer is passed as an argument to `actionFn` so that the actionFn may restart the timer to be called again the next time predicateFn returns false.
--- * See also `hs.timer.waitUntil`, which is essentially the opposite of this function
module.waitWhile = function(predicateFn, ...)
return module.waitUntil(function() return not predicateFn() end, ...)
end
--- hs.timer.doWhile(predicateFn, actionFn[, checkInterval]) -> timer
--- Constructor
--- Creates and starts a timer which will perform `actionFn` every `checkinterval` seconds while `predicateFn` returns true. The timer is automatically stopped when `predicateFn` returns false.
---
--- Parameters:
--- * predicateFn - a function which determines when to stop calling `actionFn`. This function takes no arguments, but should return false when it is time to stop calling `actionFn`.
--- * actionFn - a function which performs the desired action. This function may take a single argument, the timer itself.
--- * checkInterval - an optional parameter indicating how often to repeat the `predicateFn` check. Defaults to 1 second.
---
--- Returns:
--- * a timer object
---
--- Notes:
--- * The timer is passed as an argument to `actionFn` so that it may stop the timer prematurely (i.e. before predicateFn returns false) if desired.
--- * See also `hs.timer.doUntil`, which is essentially the opposite of this function
module.doWhile = function(predicateFn, ...)
return module.doUntil(function() return not predicateFn() end, ...)
end
--- hs.timer.localTime() -> number
--- Function
--- Returns the number of seconds since local time midnight
---
--- Parameters:
--- * None
---
--- Returns:
--- * the number of seconds
module.localTime = function()
local tnow=date('*t')
return tnow.sec+tnow.min*60+tnow.hour*3600
end
--- hs.timer.doAt(time[, repeatInterval], fn[, continueOnError]) -> timer
--- Constructor
--- Creates and starts a timer which will perform `fn` at the given (local) `time` and then (optionally) repeat it every `interval`.
---
--- Parameters:
--- * time - number of seconds after (local) midnight, or a string in the format "HH:MM" (24-hour local time), indicating
--- the desired trigger time
--- * repeatInterval - (optional) number of seconds between triggers, or a string in the format
--- "DDd", "DDdHHh", "HHhMMm", "HHh" or "MMm" indicating days, hours and/or minutes between triggers; if omitted
--- or `0` the timer will trigger only once
--- * fn - a function to call every time the timer triggers
--- * continueOnError - an optional boolean flag, defaulting to false, which indicates that the timer should not be automatically stopped if the callback function results in an error.
---
--- Returns:
--- * a timer object
---
--- Notes:
--- * The timer can trigger up to 1 second early or late
--- * The first trigger will be set to the earliest occurrence given the `repeatInterval`; if that's omitted,
--- and `time` is earlier than the current time, the timer will trigger the next day. If the repeated interval
--- results in exactly 24 hours you can schedule regular jobs that will run at the expected time independently
--- of when Hammerspoon was restarted/reloaded. E.g.:
--- * If it's 19:00, `hs.timer.doAt("20:00",somefn)` will set the timer 1 hour from now
--- * If it's 21:00, `hs.timer.doAt("20:00",somefn)` will set the timer 23 hours from now
--- * If it's 21:00, `hs.timer.doAt("20:00","6h",somefn)` will set the timer 5 hours from now (at 02:00)
--- * To run a job every hour on the hour from 8:00 to 20:00: `for h=8,20 do hs.timer.doAt(h..":00","1d",runJob) end`
module.doAt = function(time,interval,fn,continueOnError)
if type(interval)=='function' then continueOnError=fn fn=interval interval=0 end
interval=timeStringToSeconds(interval)
if interval~=0 and interval<60 then error('invalid interval',2) end -- degenerate use case for this function
time=timeStringToSeconds(time)
local now=module.localTime()
while time<=now do
time=time+(interval==0 and module.days(1) or interval)
end
local delta=time-now
time=time%86400 -- for logging
log.df('timer set for %02d:%02d:%02d, %dh%dm%ds from now',
floor(time/3600),floor(time/60)%60,floor(time%60),floor(delta/3600),floor(delta/60)%60,floor(delta%60))
return module.new(interval,fn,continueOnError):start():setNextTrigger(delta)
end
--- === hs.timer.delayed ===
---
--- Specialized timer objects to coalesce processing of unpredictable asynchronous events into a single callback
--- hs.timer.delayed:start([delay]) -> hs.timer.delayed object
--- Method
--- Starts or restarts the callback countdown
---
--- Parameters:
--- * delay - (optional) if provided, sets the countdown duration to this number of seconds
--- for this time only; subsequent calls to `:start()` will revert to the original delay (or
--- to the delay set with `:setDelay(delay)`)
---
--- Returns:
--- * the delayed timer object
--- hs.timer.delayed:stop() -> hs.timer.delayed object
--- Method
--- Cancels the callback countdown, if running; the callback will therefore not be triggered
---
--- Parameters:
--- * None
---
--- Returns:
--- * the delayed timer object
--- hs.timer.delayed:running() -> boolean
--- Method
--- Returns a boolean indicating whether the callback countdown is running
---
--- Parameters:
--- * None
---
--- Returns:
--- * a boolean
--- hs.timer.delayed:setDelay(delay) -> hs.timer.delayed object
--- Method
--- Changes the callback countdown duration
---
--- Parameters:
--- * None
---
--- Returns:
--- * the delayed timer object
---
--- Notes:
--- * if the callback countdown is running, calling this method will restart it
--- hs.timer.delayed:nextTrigger() -> number or nil
--- Method
--- Returns the time left in the callback countdown
---
--- Parameters:
--- * None
---
--- Returns:
--- * if the callback countdown is running, returns the number of seconds until it triggers; otherwise returns nil
--- hs.timer.delayed.new(delay, fn) -> hs.timer.delayed object
--- Constructor
--- Creates a new delayed timer.
---
--- Delayed timers have specialized methods that behave differently from regular timers.
--- When the `:start()` method is invoked, the timer will wait for `delay` seconds before calling `fn()`;
--- this is referred to as the callback countdown. If `:start()` is invoked again before `delay` has elapsed,
--- the countdown starts over again.
---
--- You can use a delayed timer to coalesce processing of unpredictable asynchronous events into a single
--- callback; for example, if you have an event stream that happens in "bursts" of dozens of events at once,
--- set an appropriate `delay` to wait for things to settle down, and then your callback will run just once.
---
--- Parameters:
--- * delay - number of seconds to wait for after a `:start()` invocation (the "callback countdown")
--- * fn - a function to call after `delay` has fully elapsed without any further `:start()` invocations
---
--- Returns:
--- * a new `hs.timer.delayed` object
---
--- Notes:
--- * these timers are meant to be long-lived: once instantiated, there's no way to remove them from the run loop;
--- create them once at the module level.
local DISTANT_FUTURE=315360000 -- 10 years (roughly)
module.delayed = {
new=function(delay,fn)
local tmr=module.new(DISTANT_FUTURE,fn):start()
return {
start=function(self,dl) tmr:setNextTrigger(dl or delay) return self end,
stop=function(self) tmr:setNextTrigger(DISTANT_FUTURE) return self end,
nextTrigger=function() local nt=tmr:nextTrigger() return (nt>0 and nt<=delay) and nt or nil end,
running=function(self) return self:nextTrigger() and true or false end,
setDelay=function(self,dl) if self:running() then delay=dl self:start() end delay=dl return self end,
}
end
}
-- Return Module Object --------------------------------------------------
return module
| mit |
tridge/ardupilot | libraries/AP_Scripting/examples/rgb_notify_patterns.lua | 19 | 1396 | -- This script is a test of led override
local count = 0
local num_leds = 16
-- constrain a value between limits
function constrain(v, vmin, vmax)
if v < vmin then
v = vmin
end
if v > vmax then
v = vmax
end
return v
end
--[[
Table of colors on a rainbow, red first
--]]
local rainbow = {
{ 255, 0, 0 },
{ 255, 127, 0 },
{ 255, 255, 0 },
{ 0, 255, 0 },
{ 0, 0, 255 },
{ 75, 0, 130 },
{ 143, 0, 255 },
}
--[[
Function to set a LED to a color on a classic rainbow spectrum, with v=0 giving red
--]]
function set_Rainbow(led, v)
local num_rows = #rainbow
local row = math.floor(constrain(v * (num_rows-1)+1, 1, num_rows-1))
local v0 = (row-1) / (num_rows-1)
local v1 = row / (num_rows-1)
local p = (v - v0) / (v1 - v0)
r = math.floor(rainbow[row][1] + p * (rainbow[row+1][1] - rainbow[row][1]))
g = math.floor(rainbow[row][2] + p * (rainbow[row+1][2] - rainbow[row][2]))
b = math.floor(rainbow[row][3] + p * (rainbow[row+1][3] - rainbow[row][3]))
notify:handle_rgb_id(r, g, b, led)
end
function update() -- this is the loop which periodically runs
count = count + 1
if count > 16 then
count = 0
end
for led = 0, num_leds-1 do
local v = ((count+led)%16)/16
set_Rainbow(led, v)
end
return update, 20 -- reschedules the loop in 15 seconds
end
return update() -- run immediately before starting to reschedule
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters/npcs/Panna-Donna.lua | 38 | 1038 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Panna-Donna
-- Type: Mission NPC
-- @zone: 238
-- @pos -57.502 -6 229.571
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0069);
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 |
jshackley/darkstar | scripts/globals/items/trilobite.lua | 18 | 1338 | -----------------------------------------
-- ID: 4317
-- Item: Trilobite
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 3
-- Defense +16%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4317);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_DEFP, 16);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Selbina/npcs/Quelpia.lua | 33 | 1707 | -----------------------------------
-- Area: Selbina
-- NPC: Quelpia
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,QUELPIA_SHOP_DIALOG);
stock = {0x1202,585, -- Scroll of Cure II
0x1203,3261, -- Scroll of Cure III
0x1208,10080, -- Scroll of Curaga II
0x120C,5178, -- Scroll of Raise
0x1215,31500, -- Scroll of Holy
0x1218,10080, -- Scroll of Dia II
0x121D,8100, -- Scroll of Banish II
0x122C,6366, -- Scroll of Protect II
0x1231,15840, -- Scroll of Shell II
0x1239,18000, -- Scroll of Haste
0x1264,4644, -- Scroll of Enfire
0x1265,3688, -- Scroll of Enblizzard
0x1266,2250, -- Scroll of Enaero
0x1267,1827, -- Scroll of Enstone
0x1268,1363, -- Scroll of Enthunder
0x1269,6366} -- Scroll of Enwater
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 |
jshackley/darkstar | scripts/zones/Kazham-Jeuno_Airship/TextIDs.lua | 22 | 1072 | -- 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>
-- Other
WILL_REACH_JEUNO = 7045; -- The airship will reach Jeuno in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
WILL_REACH_KAZHAM = 7046; -- The airship will reach Kazham in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
N_JEUNO_MOMENTARILY = 7047; -- We will be arriving in Jeuno momentarily.
IN_KAZHAM_MOMENTARILY = 7048; -- We will be arriving in Kazham momentarily.
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Ilrusi_Atoll/npcs/Excaliace.lua | 29 | 4503 | -----------------------------------
-- Area: Periqia
-- NPC: Excaliace
-----------------------------------
require("scripts/zones/Periqia/IDs");
require("scripts/globals/pathfind");
local start = {-322,-16.5,380};
local startToChoice1 = {
-320.349548, -16.046591, 379.684570
-318.312317, -16.046591, 379.579865
-316.286530, -16.046591, 379.472992
-314.249298, -16.048323, 379.368164
-312.212616, -16.050047, 379.263855
-310.348267, -16.057688, 378.513367
-309.100250, -16.063747, 376.912720
-307.959656, -16.077335, 375.221832
-306.816345, -16.077335, 373.532349
-305.671082, -16.077335, 371.846008
-304.516022, -16.077335, 370.168579
-303.362549, -16.077335, 368.489624
-302.209167, -16.087559, 366.807190
-301.054626, -16.087715, 365.125336
-299.976593, -16.119972, 363.402710
-299.820740, -16.189123, 361.399994
-300.012909, -16.189123, 359.369080
-300.204407, -16.189123, 357.341705
-300.397125, -16.189123, 355.314880
-300.588409, -16.189123, 353.283936
-300.780060, -16.189123, 351.253296
-300.971313, -16.191444, 349.222321
-301.163574, -16.214754, 347.192749
-301.389923, -16.229296, 345.167511
-302.813599, -16.249445, 343.574554
-304.622406, -16.276562, 342.632568
-306.459869, -16.276562, 341.757172
-308.455261, -16.276562, 341.393158
-310.489380, -16.276562, 341.389252
-312.521088, -16.279837, 341.571747
-314.551819, -16.298687, 341.754822
-316.585144, -15.753593, 341.876556
-318.621338, -15.789236, 341.765198
-320.658966, -15.779417, 341.662872
-322.697296, -15.765886, 341.574463
-324.727234, -15.980421, 341.479340
-326.660187, -16.012735, 342.099487
-328.550476, -15.933064, 342.860687
-330.435150, -15.771011, 343.625427
-332.294006, -15.696083, 344.450684
-333.912903, -16.043205, 345.705078
-335.720062, -15.788860, 346.616364
-337.668945, -15.706074, 347.100769
-339.570679, -15.741604, 346.444336
-340.824524, -15.691669, 344.865021
-341.839478, -15.428291, 343.124268
-342.645996, -15.079435, 341.120239
-342.902252, -15.113903, 339.113068
-342.625366, -15.397438, 337.113739
-342.355469, -15.772522, 335.126404
-341.725372, -16.081879, 333.186157
-341.358307, -16.052465, 331.183319
-340.988190, -15.890514, 329.183777
-340.739380, -15.852081, 327.166229
-340.652344, -15.829269, 325.153931
-340.602631, -15.811451, 323.125397
-340.650421, -15.682171, 321.093201
-340.440063, -15.661972, 318.978729
-340.534454, -15.702602, 316.816895
-340.532501, -15.702147, 314.776947
-340.536591, -15.697933, 312.737244
-340.542572, -15.670002, 310.697632
-340.545624, -15.678772, 308.657776
-340.554047, -15.631170, 306.619476
-340.412598, -15.624416, 304.459137
-340.379303, -15.661182, 302.420258
};
function onSpawn(npc)
npc:initNpcAi();
npc:pathThrough(start, PATHFLAG_REPEAT);
end;
function onPath(npc)
local instance = npc:getInstance();
local progress = instance:getProgress();
local chars = instance:getChars();
if (progress == 0) then
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
instance:setProgress(1);
npc:messageText(npc,Periqia.text.EXCALIACE_START);
npc:pathThrough(startToChoice1);
end
end
elseif (progress == 1) then
local run = true;
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
run = false;
end
end
if (run) then
npc:messageText(npc,Periqia.text.EXCALIACE_RUN);
end
end
-- go back and forth the set path
-- pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/mobskills/Antimatter.lua | 1 | 1134 | ---------------------------------------------------
-- Antimatter
--
-- Description: Single-target ranged Light damage (~700-1500), ignores Utsusemi.
-- Type: Magical
--
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobID = mob:getID(); --(16908295 ,16908302 ,16908309 = ultima , 16928966=proto-ultima )
local mobhp = mob:getHPP();
local phase = mob:getLocalVar("battlePhase");
if ((mobID == 16928966 and phase < 4) or ((mobID == 16908295 or mobID == 16908302 or mobID == 16908309) and mobhp < 20)) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 2.5;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_LIGHT,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_LIGHT,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Kazham/npcs/Tsahbi_Ifalombo.lua | 15 | 1099 | -----------------------------------
-- Area: Kazham
-- NPC: Tsahbi Ifalombo
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00B4); -- scent from Blue Rafflesias
else
player:startEvent(0x005A);
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 |
Guard13007/Particle | src/Generate.lua | 1 | 1851 | require "Particle"
function Generate()
if world then world:destroy() end
world = love.physics.newWorld(0, 0, true)
require "physCallbacks"
world:setCallbacks(beginContact, endContact, preSolve, postSolve)
--particles = {}
if particles then
for i=1,#particles do
--particles[i].delete()
for k,_ in pairs(particles[i]) do
particles[i][k] = nil
end
end
end
particles = {}
Particle.reset()
for i=1,100 do
local x = love.math.random(6, love.graphics.getWidth() - 6)
local y = love.math.random(6, love.graphics.getHeight() - 6)
particles[i] = Particle.new(math.floor(love.math.random(1, 200)), x, y)
local fx = love.math.random(-50000, 50000)
local fy = love.math.random(-50000, 50000)
particles[i].applyForce(fx, fy)
end
local box = {}
local w,h = love.graphics.getDimensions()
box.ground = {}
box.ground.body = love.physics.newBody(world, w/2, 0, "static")
box.ground.shape = love.physics.newEdgeShape(-w/2, h, w/2, h)
box.ground.fixture = love.physics.newFixture(box.ground.body, box.ground.shape)
box.ground.fixture:setRestitution(1)
box.roof = {}
box.roof.body = love.physics.newBody(world, w/2, 0, "static")
box.roof.shape = love.physics.newEdgeShape(-w/2, 0, w/2, 0)
box.roof.fixture = love.physics.newFixture(box.roof.body, box.roof.shape)
box.roof.fixture:setRestitution(1)
box.left = {}
box.left.body = love.physics.newBody(world, 0, h/2, "static")
box.left.shape = love.physics.newEdgeShape(0, -h/2, 0, h/2)
box.left.fixture = love.physics.newFixture(box.left.body, box.left.shape)
box.left.fixture:setRestitution(1)
box.right = {}
box.right.body = love.physics.newBody(world, 0, h/2, "static")
box.right.shape = love.physics.newEdgeShape(w, -h/2, w, h/2)
box.right.fixture = love.physics.newFixture(box.right.body, box.right.shape)
box.right.fixture:setRestitution(1)
end
| gpl-2.0 |
Shrike78/Shilke2D | Shilke2D/Tween/TweenParallel.lua | 1 | 1424 | --[[---
A TweenParallel is a group of tween executed simultaneously.
@usage
p = Tween.parallel(t1,t2,t3)
where t1,t2,t3 are different tweens
--]]
local TweenParallel = class(Tween)
Tween.parallel = TweenParallel
---Constructor
--@param ... list of tweens to be parallelized
function TweenParallel:init(...)
Tween.init(self)
self.tweenList = {}
self.completed = {}
self.numOfCompleted = 0
self:add(...)
end
---Adds tweens to the parallel list
--@param ... list of tweens to be parallelized
function TweenParallel:add(...)
local args = {...}
for _,v in pairs(args) do
assert(v:is_a(Tween))
v:addEventListener(Event.REMOVE_FROM_JUGGLER, self.onRemoveEvent,self)
table.insert(self.tweenList,v)
end
end
---Resets the tween and all the tweens it's handling
function TweenParallel:reset()
Tween.reset(self)
table.clear(self.completed)
self.numOfCompleted = 0
for _,t in ipairs(self.tweenList) do
t:reset()
end
end
function TweenParallel:onRemoveEvent(e)
self.completed[e.sender] = true
self.numOfCompleted = self.numOfCompleted + 1
end
function TweenParallel:_start()
assert(#self.tweenList > 1, "tween parallel should handle at least 2 tweens")
end
function TweenParallel:_update(deltaTime)
for _,v in pairs(self.tweenList) do
if not self.completed[v] then
v:advanceTime(deltaTime)
end
end
end
function TweenParallel:_isCompleted()
return (self.numOfCompleted == #self.tweenList)
end
| mit |
Ombridride/minetest-minetestforfun-server | mods/mobs/bee.lua | 7 | 4309 |
-- Bee by KrupnoPavel
mobs:register_mob("mobs:bee", {
-- animal, monster, npc, barbarian
type = "animal",
-- it is aggressive
passive = true,
-- health & armor
hp_min = 1,
hp_max = 2,
armor = 200,
-- textures and model
collisionbox = {-0.2, -0.01, -0.2, 0.2, 0.2, 0.2},
visual = "mesh",
mesh = "mobs_bee.x",
textures = {
{"mobs_bee.png"},
},
-- sounds
makes_footstep_sound = false,
sounds = {
random = "mobs_bee",
},
walk_velocity = 1,
jump = true,
-- drops honey when killed
drops = {
{name = "mobs:honey", chance = 1, min = 1, max = 2},
},
-- damage
water_damage = 1,
lava_damage = 1,
light_damage = 0,
fall_damage = 0,
fall_speed = -3,
-- model animation
animation = {
speed_normal = 15,
stand_start = 0,
stand_end = 30,
walk_start = 35,
walk_end = 65,
},
-- right click to pick up bee
on_rightclick = function(self, clicker)
mobs:capture_mob(self, clicker, 25, 80, 0, true, nil)
end,
})
-- spawn on group:flowers between 4 and 20 light, 1 in 8000 chance, 1 bee in area up to 31000 in height
mobs:spawn_specific("mobs:bee", {"group:flower"}, {"air"}, 4, 20, 30, 8000, 2, -31000, 31000, true, true)
-- register spawn egg
mobs:register_egg("mobs:bee", "Bee", "mobs_bee_inv.png", 1)
-- honey
minetest.register_craftitem("mobs:honey", {
description = "Honey",
inventory_image = "mobs_honey_inv.png",
on_use = minetest.item_eat(6),
})
-- beehive (when placed spawns bee)
minetest.register_node("mobs:beehive", {
description = "Beehive",
drawtype = "plantlike",
visual_scale = 1.0,
tiles = {"mobs_beehive.png"},
inventory_image = "mobs_beehive.png",
paramtype = "light",
sunlight_propagates = true,
walkable = true,
groups = {fleshy=3,dig_immediate=3},
on_use = minetest.item_eat(4),
sounds = default.node_sound_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", "size[8,6]"
..default.gui_bg..default.gui_bg_img..default.gui_slots
.. "image[3,0.8;0.8,0.8;mobs_bee_inv.png]"
.. "list[current_name;beehive;4,0.5;1,1;]"
.. "list[current_player;main;0,2.35;8,4;]"
.. "listring[]")
meta:get_inventory():set_size("beehive", 1)
end,
after_place_node = function(pos, placer, itemstack)
if placer:is_player() then
minetest.set_node(pos, {name = "mobs:beehive", param2 = 1})
if math.random(1, 5) == 1 then
minetest.add_entity(pos, "mobs:bee")
end
end
end,
on_punch = function(pos, node, puncher)
-- yep, bee's don't like having their home punched by players
puncher:set_hp(puncher:get_hp() - 4)
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if listname == "beehive" then
return 0
end
return stack:get_count()
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos)
-- only dig beehive if no honey inside
return meta:get_inventory():is_empty("beehive")
end,
})
minetest.register_craft({
output = "mobs:beehive",
recipe = {
{"mobs:bee","mobs:bee","mobs:bee"},
}
})
-- honey block
minetest.register_node("mobs:honey_block", {
description = "Honey Block",
tiles = {"mobs_honey_block.png"},
groups = {snappy = 3, flammable = 2},
sounds = default.node_sound_dirt_defaults(),
})
minetest.register_craft({
output = "mobs:honey_block",
recipe = {
{"mobs:honey", "mobs:honey", "mobs:honey"},
{"mobs:honey", "mobs:honey", "mobs:honey"},
{"mobs:honey", "mobs:honey", "mobs:honey"},
}
})
minetest.register_craft({
output = "mobs:honey 9",
recipe = {
{"mobs:honey_block"},
}
})
-- beehive workings
minetest.register_abm({
nodenames = {"mobs:beehive"},
interval = 6,
chance = 5,
catch_up = false,
action = function(pos, node)
-- bee's only make honey during the day
local tod = (minetest.get_timeofday() or 0) * 24000
if tod < 4500 or tod > 19500 then
return
end
-- find flowers in area around hive
local flowers = minetest.find_nodes_in_area_under_air(
{x = pos.x - 10, y = pos.y - 5, z = pos.z - 10},
{x = pos.x + 10, y = pos.y + 5, z = pos.z + 10},
"group:flower")
-- no flowers no honey, nuff said!
if #flowers > 3 then
local meta = minetest.get_meta(pos)
-- error check just incase it's an old beehive
if meta then
meta:get_inventory():add_item("beehive", "mobs:honey")
end
end
end
})
| unlicense |
jshackley/darkstar | scripts/globals/abilities/steal.lua | 18 | 3294 | -----------------------------------
-- Ability: Steal
-- Steal items from enemy.
-- Obtained: Thief Level 5
-- Recast Time: 5:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-- these are the quadavs that the thf af1 item can be stolen from
-- bronze quadav groupid = 7949
-- garnet quadav groupid = 7960
-- silver quadav groupid = 7977
-- zircorn quadav groupid = 7985
validThfQuestMobs = {17379367,17379368,17379459,17379470,17379477,17379489,17379493,17379495,17379501,17379505,17379509,
17379513,17379517,17379521,17379525,17379529,17379533,17379538,17379543,17379547,17379552,17379556,
17379560,17379565,17379569,17379573,17379577,17379581,17379585,17379597,17379363,17379364,17379462,
17379473,17379480,17379496,17379498,17379500,17379504,17379508,17379512,17379516,17379520,17379524,
17379528,17379532,17379536,17379541,17379546,17379550,17379555,17379559,17379563,17379568,17379572,
17379576,17379580,17379584,17379588,17379600,17379361,17379362,17379460,17379471,17379478,17379490,
17379491,17379497,17379502,17379506,17379510,17379514,17379518,17379522,17379526,17379530,17379534,
17379539,17379544,17379548,17379553,17379557,17379561,17379566,17379570,17379574,17379578,17379582,
17379586,17379598,17379365,17379366,17379461,17379472,17379479,17379492,17379494,17379499,17379503,
17379507,17379511,17379515,17379519,17379523,17379527,17379531,17379535,17379540,17379545,17379549,
17379554,17379558,17379562,17379567,17379571,17379575,17379579,17379583,17379587,17379599};
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getFreeSlotsCount() == 0) then
return MSGBASIC_FULL_INVENTORY,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local thfLevel;
local stolen = 0;
if (player:getMainJob() == JOB_THF) then
thfLevel = player:getMainLvl();
else
thfLevel = player:getSubLvl();
end
local stealMod = player:getMod(MOD_STEAL);
local stealChance = 50 + stealMod * 2 + thfLevel - target:getMainLvl();
stolen = target:getStealItem();
if (target:isMob() and math.random(100) < stealChance and stolen ~= 0) then
if (checkThfAfQuest(player, target) == true) then
stolen = 4569;
end
player:addItem(stolen);
target:itemStolen();
ability:setMsg(125); -- Item stolen successfully
else
ability:setMsg(153); -- Failed to steal
end
return stolen;
end;
function checkThfAfQuest(player, target)
local targid = target:getID();
if (player:getVar("theTenshodoShowdownCS") == 3) then
for key, value in pairs(validThfQuestMobs) do
if value == targid then
return true
end
end
return false
end
end; | gpl-3.0 |
asmagill/hs._asm.luathread | luaskin/modules/styledtext/init.lua | 10 | 31621 | --- === hs.styledtext ===
---
--- This module adds support for controlling the style of the text in Hammerspoon.
---
--- More detailed documentation is being worked on and will be provided in the Hammerspoon Wiki at https://github.com/Hammerspoon/hammerspoon/wiki. The documentation here is a condensed version provided for use within the Hammerspoon Dash docset and the inline help provided by the `help` console command within Hammerspoon.
---
--- The following list of attributes key-value pairs are recognized by this module and can be adjusted, set, or removed for objects by the various methods provided by this module. The list of attributes is provided here for reference; anywhere in the documentation you see a reference to the `attributes key-value pairs`, refer back to here for specifics:
---
--- * `font` - A table containing the font name and size, specified by the keys `name` and `size`. Default is the System Font at 27 points for `hs.drawing` text objects; otherwise the default is Helvetica at 12 points. You may also specify this as a string, which will be taken as the font named in the string at the default size, when setting this attribute.
--- * `color` - A table indicating the color of the text as described in `hs.drawing.color`. Default is white for hs.drawing text objects; otherwise the default is black.
--- * `backgroundColor` - Default nil, no background color (transparent).
--- * `underlineColor` - Default nil, same as `color`.
--- * `strikethroughColor` - Default nil, same as `color`.
--- * `strokeColor` - Default nil, same as `color`.
--- * `strokeWidth` - Default 0, no stroke; positive, stroke alone; negative, stroke and fill (a typical value for outlined text would be 3.0)
--- * `paragraphStyle` - A table containing the paragraph style. This table may contain any number of the following keys:
--- * `alignment` - A string indicating the texts alignment. The string may contain a value of "left", "right", "center", "justified", or "natural". Default is "natural".
--- * `lineBreak` - A string indicating how text that doesn't fit into the drawingObjects rectangle should be handled. The string may be one of "wordWrap", "charWrap", "clip", "truncateHead", "truncateTail", or "truncateMiddle". Default is "wordWrap".
--- * `baseWritingDirection` - A string indicating the base writing direction for the lines of text. The string may be one of "natural", "leftToRight", or "rightToLeft". Default is "natural".
--- * `tabStops` - An array of defined tab stops. Default is an array of 12 left justified tab stops 28 points apart. Each element of the array may contain the following keys:
--- * `location` - A floating point number indicating the number of points the tab stap is located from the line's starting margin (see baseWritingDirection).
--- * `tabStopType` - A string indicating the type of the tab stop: "left", "right", "center", or "decimal"
--- * `defaultTabInterval` - A positive floating point number specifying the default tab stop distance in points after the last assigned stop in the tabStops field.
--- * `firstLineHeadIndent` - A positive floating point number specifying the distance, in points, from the leading margin of a frame to the beginning of the paragraph's first line. Default 0.0.
--- * `headIndent` - A positive floating point number specifying the distance, in points, from the leading margin of a text container to the beginning of lines other than the first. Default 0.0.
--- * `tailIndent` - A floating point number specifying the distance, in points, from the margin of a frame to the end of lines. If positive, this value is the distance from the leading margin (for example, the left margin in left-to-right text). If 0 or negative, it's the distance from the trailing margin. Default 0.0.
--- * `maximumLineHeight` - A positive floating point number specifying the maximum height that any line in the frame will occupy, regardless of the font size. Glyphs exceeding this height will overlap neighboring lines. A maximum height of 0 implies no line height limit. Default 0.0.
--- * `minimumLineHeight` - A positive floating point number specifying the minimum height that any line in the frame will occupy, regardless of the font size. Default 0.0.
--- * `lineSpacing` - A positive floating point number specifying the space in points added between lines within the paragraph (commonly known as leading). Default 0.0.
--- * `paragraphSpacing` - A positive floating point number specifying the space added at the end of the paragraph to separate it from the following paragraph. Default 0.0.
--- * `paragraphSpacingBefore` - A positive floating point number specifying the distance between the paragraph's top and the beginning of its text content. Default 0.0.
--- * `lineHeightMultiple` - A positive floating point number specifying the line height multiple. The natural line height of the receiver is multiplied by this factor (if not 0) before being constrained by minimum and maximum line height. Default 0.0.
--- * `hyphenationFactor` - The hyphenation factor, a value ranging from 0.0 to 1.0 that controls when hyphenation is attempted. By default, the value is 0.0, meaning hyphenation is off. A factor of 1.0 causes hyphenation to be attempted always.
--- * `tighteningFactorForTruncation` - A floating point number. When the line break mode specifies truncation, the system attempts to tighten inter character spacing as an alternative to truncation, provided that the ratio of the text width to the line fragment width does not exceed 1.0 + the value of tighteningFactorForTruncation. Otherwise the text is truncated at a location determined by the line break mode. The default value is 0.05.
--- * `headerLevel` - An integer number from 0 to 6 inclusive which specifies whether the paragraph is to be treated as a header, and at what level, for purposes of HTML generation. Defaults to 0.
--- * `superscript` - An integer indicating if the text is to be displayed as a superscript (positive) or a subscript (negative) or normal (0).
--- * `ligature` - An integer. Default 1, standard ligatures; 0, no ligatures; 2, all ligatures.
--- * `strikethroughStyle` - An integer representing the strike-through line style. See `hs.styledtext.lineStyles`, `hs.styledtext.linePatterns` and `hs.styledtext.lineAppliesTo`.
--- * `underlineStyle` - An integer representing the underline style. See `hs.styledtext.lineStyles`, `hs.styledtext.linePatterns` and `hs.styledtext.lineAppliesTo`.
--- * `baselineOffset` - A floating point value, as points offset from baseline. Default 0.0.
--- * `kerning` - A floating point value, as points by which to modify default kerning. Default nil to use default kerning specified in font file; 0.0, kerning off; non-zero, points by which to modify default kerning.
--- * `obliqueness` - A floating point value, as skew to be applied to glyphs. Default 0.0, no skew.
--- * `expansion` - A floating point value, as log of expansion factor to be applied to glyphs. Default 0.0, no expansion.
--- * `shadow` - Default nil, indicating no drop shadow. A table describing the drop shadow effect for the text. The table may contain any of the following keys:
--- * `offset` - A table with `h` and `w` keys (a size structure) which specify horizontal and vertical offsets respectively for the shadow. Positive values always extend down and to the right from the user's perspective.
--- * `blurRadius` - A floating point value specifying the shadow's blur radius. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. The default value is 0.
--- * `color` - The default shadow color is black with an alpha of 1/3. If you set this property to nil, the shadow is not drawn.
---
--- To make the `hs.styledtext` objects easier to use, in addition to the module specific functions and methods defined, some of the Lua String library has been reproduced to perform similar functions on these objects. See the help section for each method for more information on their use:
---
--- * `hs.styledtext:byte`
--- * `hs.styledtext:find`
--- * `hs.styledtext:gmatch`
--- * `hs.styledtext:len`
--- * `hs.styledtext:lower`
--- * `hs.styledtext:match`
--- * `hs.styledtext:rep`
--- * `hs.styledtext:sub`
--- * `hs.styledtext:upper`
---
--- In addition, the following metamethods have been included:
---
--- * concat:
--- * `string`..`object` yields the string values concatenated
--- * `object`..`string` yields a new `hs.styledtext` object with `string` appended
--- * two `hs.styledtext` objects yields a new `hs.styledtext` object containing the concatenation of the two objects
--- * len: #object yields the length of the text contained in the object
--- * eq: object ==/~= object yields a boolean indicating if the text of the two objects is equal or not. Use `hs.styledtext:isIdentical` if you need to compare attributes as well.
--- * lt, le: allows <, >, <=, and >= comparisons between objects and strings in which the text of an object is compared with the text of another or a Lua string.
---
--- Note that due to differences in the way Lua determines when to use metamethods for equality comparisons versus relative-position comparisons, ==/~= cannot compare an object to a Lua string (it will always return false because the types are different). You must use object:getString() ==/~= `string`. (see `hs.styledtext:getString`)
local module = require("hs.styledtext.internal")
require("hs.drawing.color") -- make sure that the conversion helpers required to support color are loaded
-- private variables and methods -----------------------------------------
local _kMetaTable = {}
_kMetaTable._k = {}
_kMetaTable.__index = function(obj, key)
if _kMetaTable._k[obj] then
if _kMetaTable._k[obj][key] then
return _kMetaTable._k[obj][key]
else
for k,v in pairs(_kMetaTable._k[obj]) do
if v == key then return k end
end
end
end
return nil
end
_kMetaTable.__newindex = function(obj, key, value)
error("attempt to modify a table of constants",2)
return nil
end
_kMetaTable.__pairs = function(obj) return pairs(_kMetaTable._k[obj]) end
_kMetaTable.__tostring = function(obj)
local result = ""
if _kMetaTable._k[obj] then
local width = 0
for k,v in pairs(_kMetaTable._k[obj]) do width = width < #k and #k or width end
for k,v in require("hs.fnutils").sortByKeys(_kMetaTable._k[obj]) do
result = result..string.format("%-"..tostring(width).."s %s\n", k, tostring(v))
end
else
result = "constants table missing"
end
return result
end
_kMetaTable.__metatable = _kMetaTable -- go ahead and look, but don't unset this
local _makeConstantsTable = function(theTable)
local results = setmetatable({}, _kMetaTable)
_kMetaTable._k[results] = theTable
return results
end
local _arrayWrapper = function(results)
return setmetatable(results, { __tostring=function(_)
local results = ""
for i,v in ipairs(_) do results = results..v.."\n" end
return results
end})
end
local _tableWrapper = function(results)
local __tableWrapperFunction
__tableWrapperFunction = function(_)
local result = ""
local width = 0
for k,v in pairs(_) do width = width < #k and #k or width end
for k,v in require("hs.fnutils").sortByKeys(_) do
result = result..string.format("%-"..tostring(width).."s ", k)
if type(v) == "table" then
result = result..__tableWrapperFunction(v):gsub("[ \n]", {[" "] = "=", ["\n"] = " "}).."\n"
else
result = result..tostring(v).."\n"
end
end
return result
end
return setmetatable(results, { __tostring=__tableWrapperFunction })
end
local internalFontFunctions = {
fontNames = module.fontNames,
fontNamesWithTraits = module.fontNamesWithTraits,
fontInfo = module.fontInfo,
}
-- Public interface ------------------------------------------------------
-- tweak the hs.styledtext object metatable with things easier to do in lua...
local objectMetatable = hs.getObjectMetatable("hs.styledtext")
--- hs.styledtext:byte([starts], [ends]) -> integer, ...
--- Method
--- Returns the internal numerical representation of the characters in the `hs.styledtext` object specified by the given indicies. Mimics the Lua `string.byte` function.
---
--- Parameters:
--- * starts - an optional index position within the text of the `hs.styledtext` object indicating the beginning of the substring to return numerical values for. Defaults to 1, the beginning of the objects text. If this number is negative, it is counted backwards from the end of the object's text (i.e. -1 would be the last character position).
--- * ends - an optional index position within the text of the `hs.styledtext` object indicating the end of the substring to return numerical values for. Defaults to the value of `starts`. If this number is negative, it is counted backwards from the end of the object's text.
---
--- Returns:
--- * a list of integers representing the internal numeric representation of the characters in the `hs.styledtext` object specified by the given indicies.
---
--- Notes:
--- * `starts` and `ends` follow the conventions of `i` and `j` for Lua's `string.sub` function.
objectMetatable.byte = function(self, ...) return self:getString():byte(...) end
--- hs.styledtext:find(pattern, [init, [plain]]) -> start, end, ... | nil
--- Method
--- Returns the indicies of the first occurrence of the specified pattern in the text of the `hs.styledtext` object. Mimics the Lua `string.find` function.
---
--- Parameters:
--- * pattern - a string containing the pattern to locate. See the Lua manual, section 6.4.1 (`help.lua._man._6_4_1`) for more details.
--- * init - an optional integer specifying the location within the text to start the pattern search
--- * plain - an optional boolean specifying whether or not to treat the pattern as plain text (i.e. an exact match). Defaults to false. If you wish to specify this argument, you must also specify init.
---
--- Returns:
--- * if a match is found, `start` and `end` will be the indices where the pattern was first located. If captures were specified in the pattern, they will also be returned as additional arguments after `start` and `end`. If the pattern was not found in the text, then this method returns nil.
---
--- Notes:
--- * Any captures returned are returned as Lua Strings, not as `hs.styledtext` objects.
objectMetatable.find = function(self, ...) return self:getString():find(...) end
--- hs.styledtext:match(pattern, [init]) -> match ... | nil
--- Method
--- Returns the first occurrence of the captures in the specified pattern (or the complete pattern, if no captures are specified) in the text of the `hs.styledtext` object. Mimics the Lua `string.match` function.
---
--- Parameters:
--- * pattern - a string containing the pattern to locate. See the Lua manual, section 6.4.1 (`help.lua._man._6_4_1`) for more details.
--- * init - an optional integer specifying the location within the text to start the pattern search
---
--- Returns:
--- * if a match is found, the captures in the specified pattern (or the complete pattern, if no captures are specified). If the pattern was not found in the text, then this method returns nil.
---
--- Notes:
--- * Any captures (or the entire pattern) returned are returned as Lua Strings, not as `hs.styledtext` objects.
objectMetatable.match = function(self, ...) return self:getString():match(...) end
--- hs.styledtext:gmatch(pattern) -> iterator-function
--- Method
--- Returns an iterator function which will return the captures (or the entire pattern) of the next match of the specified pattern in the text of the `hs.styledtext` object each time it is called. Mimics the Lua `string.gmatch` function.
---
--- Parameters:
--- * pattern - a string containing the pattern to locate. See the Lua manual, section 6.4.1 (`help.lua._man._6_4_1`) for more details.
---
--- Returns:
--- * an iterator function which will return the captures (or the entire pattern) of the next match of the specified pattern in the text of the `hs.styledtext` object each time it is called.
---
--- Notes:
--- * Any captures (or the entire pattern) returned by the iterator are returned as Lua Strings, not as `hs.styledtext` objects.
objectMetatable.gmatch = function(self, ...) return self:getString():gmatch(...) end
--- hs.styledtext:rep(n, [separator]) -> styledText object
--- Method
--- Returns an `hs.styledtext` object which contains `n` repetitions of the `hs.styledtext` object, optionally with `separator` between each repetition. Mimics the Lua `string.rep` function.
---
--- Parameters:
--- * n - the number of times to repeat the `hs.styledtext` object.
--- * separator - an optional string or `hs.styledtext` object to insert between repetitions.
---
--- Returns:
--- * an `hs.styledtext` object which contains `n` repitions of the object, including `separator` between repetitions, if it is specified.
objectMetatable.rep = function(self, n, sep)
if n < 1 then return module.new("") end
local i, result = 1, self:copy()
while (i < n) do
if sep then result = result:replaceSubstring(sep, #result + 1, 0) end
result = result..self
i = i + 1
end
return result
end
-- string.format is hs.styletext.new(string.format(...)) sufficient?
-- string.reverse reversing styles, attachment anchors, etc. do not present an obvious solution...
-- string.gsub replaces substrings internally... no obvious simple solution that maintains/supports styles...
-- string.char hs.styledtext.new(string.char(...)) is more clear as to what's intended
-- string.dump makes no sense in the context of styled strings
-- string.pack makes no sense in the context of styled strings
-- string.packsize makes no sense in the context of styled strings
-- string.unpack makes no sense in the context of styled strings
-- font stuff documented in internal.m
module.fontTraits = _makeConstantsTable(module.fontTraits)
module.linePatterns = _makeConstantsTable(module.linePatterns)
module.lineStyles = _makeConstantsTable(module.lineStyles)
module.lineAppliesTo = _makeConstantsTable(module.lineAppliesTo)
module.fontNames = function(...)
return _arrayWrapper(internalFontFunctions.fontNames(...))
end
module.fontNamesWithTraits = function(...)
return _arrayWrapper(internalFontFunctions.fontNamesWithTraits(...))
end
module.fontInfo = function(...)
return _tableWrapper(internalFontFunctions.fontInfo(...))
end
--- hs.styledtext.ansi(string, [attributes]) -> styledText object
--- Constructor
--- Create an `hs.styledtext` object from the string provided, converting ANSI SGR color and some font sequences into the appropriate attributes. Attributes to apply to the resulting string may also be optionally provided.
---
--- Parameters:
--- * string - The string containing the text with ANSI SGR sequences to be converted.
--- * attributes - an optional table containing attribute key-value pairs to apply to the entire `hs.styledtext` object to be returned.
---
--- Returns:
--- * an `hs.styledtext` object
---
--- Notes:
--- * Because a font is required for the SGR sequences indicating Bold and Italic, the base font is determined using the following logic:
--- * * if no `attributes` table is provided, the font is assumed to be the default for `hs.drawing` as returned by the `hs.drawing.defaultTextStyle` function
--- * * if an `attributes` table is provided and it defines a `font` attribute, this font is used.
--- * * if an `attributes` table is provided, but it does not provide a `font` attribute, the NSAttributedString default of Helvetica at 12 points is used.
--- * As the most common use of this constructor is likely to be from the output of a terminal shell command, you will most likely want to specify a fixed-pitch (monospace) font. You can get a list of installed fixed-pitch fonts by typing `hs.styledtext.fontNamesWithTraits(hs.styledtext.fontTraits.fixedPitchFont)` into the Hammerspoon console.
---
--- * See the module description documentation (`help.hs.styledtext`) for a description of the attributes table format which can be provided for the optional second argument.
---
--- * This function was modeled after the ANSIEscapeHelper.m file at https://github.com/balthamos/geektool-3 in the /NerdTool/classes directory.
module.ansi = function(rawText, attr)
local drawing = require("hs.drawing")
local color = require("hs.drawing.color")
local sgrCodeToAttributes = {
[ 0] = { adjustFontStyle = "remove",
backgroundColor = "remove",
color = "remove",
underlineStyle = "remove",
strikethroughStyle = "remove",
},
[ 1] = { adjustFontStyle = true }, -- increased intensity; generally bold, if the font isn't already
[ 2] = { adjustFontStyle = false }, -- fainter intensity; generally not available in fixed pitch fonts, but try
[ 3] = { adjustFontStyle = module.fontTraits.italicFont },
[ 22] = { adjustFontStyle = "remove" },
[ 4] = { underlineStyle = module.lineStyles.single },
[ 21] = { underlineStyle = module.lineStyles.double },
[ 24] = { underlineStyle = module.lineStyles.none },
[ 9] = { strikethroughStyle = module.lineStyles.single },
[ 29] = { strikethroughStyle = module.lineStyles.none },
[ 30] = { color = { list = "ansiTerminalColors", name = "fgBlack" } },
[ 31] = { color = { list = "ansiTerminalColors", name = "fgRed" } },
[ 32] = { color = { list = "ansiTerminalColors", name = "fgGreen" } },
[ 33] = { color = { list = "ansiTerminalColors", name = "fgYellow" } },
[ 34] = { color = { list = "ansiTerminalColors", name = "fgBlue" } },
[ 35] = { color = { list = "ansiTerminalColors", name = "fgMagenta" } },
[ 36] = { color = { list = "ansiTerminalColors", name = "fgCyan" } },
[ 37] = { color = { list = "ansiTerminalColors", name = "fgWhite" } },
-- if we want to add more colors (not official ANSI, but somewhat supported):
-- 38;5;#m for 256 colors (supported in OSX Terminal and in xterm)
-- 38;2;#;#;#m for rgb color (not in Terminal, but is in xterm)
-- [ 38] = { color = "special" },
[ 39] = { color = "remove" },
[ 90] = { color = { list = "ansiTerminalColors", name = "fgBrightBlack" } },
[ 91] = { color = { list = "ansiTerminalColors", name = "fgBrightRed" } },
[ 92] = { color = { list = "ansiTerminalColors", name = "fgBrightGreen" } },
[ 93] = { color = { list = "ansiTerminalColors", name = "fgBrightYellow" } },
[ 94] = { color = { list = "ansiTerminalColors", name = "fgBrightBlue" } },
[ 95] = { color = { list = "ansiTerminalColors", name = "fgBrightMagenta" } },
[ 96] = { color = { list = "ansiTerminalColors", name = "fgBrightCyan" } },
[ 97] = { color = { list = "ansiTerminalColors", name = "fgBrightWhite" } },
[ 40] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBlack" } },
[ 41] = { backgroundColor = { list = "ansiTerminalColors", name = "bgRed" } },
[ 42] = { backgroundColor = { list = "ansiTerminalColors", name = "bgGreen" } },
[ 43] = { backgroundColor = { list = "ansiTerminalColors", name = "bgYellow" } },
[ 44] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBlue" } },
[ 45] = { backgroundColor = { list = "ansiTerminalColors", name = "bgMagenta" } },
[ 46] = { backgroundColor = { list = "ansiTerminalColors", name = "bgCyan" } },
[ 47] = { backgroundColor = { list = "ansiTerminalColors", name = "bgWhite" } },
-- if we want to add more colors (not official ANSI, but somewhat supported):
-- 48;5;#m for 256 colors (supported in OSX Terminal and in xterm)
-- 48;2;#;#;#m for rgb color (not in Terminal, but is in xterm)
-- [ 48] = { backgroundColor = "special" },
[ 49] = { backgroundColor = "remove" },
[100] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightBlack" } },
[101] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightRed" } },
[102] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightGreen" } },
[103] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightYellow" } },
[104] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightBlue" } },
[105] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightMagenta" } },
[106] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightCyan" } },
[107] = { backgroundColor = { list = "ansiTerminalColors", name = "bgBrightWhite" } },
}
assert(type(rawText) == "string", "string expected")
-- used for font bold and italic changes.
-- if no attr table is specified, assume the hs.drawing default font
-- if a table w/out font is specified, assume the NSAttributedString default (Helvetica at 12.0)
local baseFont
if type(attr) == "nil" then baseFont = drawing.defaultTextStyle().font end
local baseFont = baseFont or (attr and attr.font) or { name = "Helvetica", size = 12.0 }
-- generate clean string and locate ANSI codes
local cleanString = ""
local formatCodes = {}
local index = 1
while true do
local s, e = rawText:find("\27[", index, true) -- why does lua support inline decimal and inline hex but not inline octal for control characters?
if s then
local code, codes = 0, {}
local incodeIndex = 1
while true do
local c = rawText:sub(e + incodeIndex, e + incodeIndex):byte()
if 48 <= c and c <= 57 then -- "0" - "9"
code = (code == 0) and (c - 48) or (code * 10 + (c - 48))
elseif c == 109 then -- "m", the terminator for SGR
table.insert(codes, code)
break
elseif c == 59 then -- ";" multi-code sequence separator
table.insert(codes, code)
code = 0
elseif 64 <= c and c <= 126 then -- other terminators indicate this is a sequence we ignore
codes = {}
break
end
incodeIndex = incodeIndex + 1
end
cleanString = cleanString .. rawText:sub(index, s - 1)
if #codes > 0 then
for i = 1, #codes, 1 do
table.insert(formatCodes, { #cleanString + 1, codes[i] })
end
end
index = e + incodeIndex + 1
else
cleanString = cleanString .. rawText:sub(index)
break
end
end
-- Should be handled by obj-c methods now...
-- -- lua indexes strings by byte; NSAttributedString by unicode character... this is a stopgap, as
-- -- I'm leaning towards the solution really belonging in the C portion of the code sine the whole
-- -- point is to extend Lua...
-- local unicodeMapping = {}
-- local i, s, e = 1, 1, 1
-- while (s <= #cleanString) do
-- s, e = cleanString:find(utf8.charpattern, s)
-- -- print(i, s, e)
-- for j = s, e, 1 do
-- unicodeMapping[j] = i
-- end
-- i = i + 1
-- s = e + 1
-- end
-- create base string with clean string and specified attributes, if any
local newString = module.new(cleanString, attr or {})
-- iterate through codes and determine what style attributes to apply
for i = 1, #formatCodes, 1 do
local s, code = formatCodes[i][1], formatCodes[i][2]
if code ~= 0 then -- skip reset everything code
local action = sgrCodeToAttributes[code]
if action then -- only do codes we recognize
for k, v in pairs(action) do
if not(type(v) == "string" and v == "remove") then -- skip placeholder to turn something off
local e, newAttribute = #cleanString, {} -- end defaults to the end of the string
-- scan for what turns us off
for j = i + 1, #formatCodes, 1 do
local nextAction = sgrCodeToAttributes[formatCodes[j][2]]
if nextAction[k] then
e = formatCodes[j][1] - 1 -- adjust the actual end point since something later resets it
break
end
end
-- NOTE: If support for 256 and/or RGB color is added, remember to adjust i here because we'll actually need to use
-- multiple entries in formatCodes to determine which color was specified.
-- apply the style now that we have an end point
if k == "adjustFontStyle" then
newAttribute.font = module.convertFont(baseFont, v)
else
newAttribute[k] = v
end
-- newString = newString:setStyle(newAttribute, unicodeMapping[s], unicodeMapping[e])
newString = newString:setStyle(newAttribute, s, e)
end
end
end
end
end
return newString
end
-- Return Module Object --------------------------------------------------
return setmetatable(module, {
__index = function(self, _)
if _ == "defaultFonts" then
local results = self._defaultFonts()
for k, v in pairs(results) do
results[k] = setmetatable(v, { __tostring = function(_)
return "{ name = ".._.name..", size = "..tostring(_.size).." }"
end
})
end
return setmetatable(results, { __tostring = function(_)
local result = ""
local width = 0
for k,v in pairs(_) do width = width < #k and #k or width end
for k,v in require("hs.fnutils").sortByKeys(_) do
result = result..string.format("%-"..tostring(width).."s %s\n", k, tostring(v))
end
return result
end
})
else
return self[_]
end
end
})
| mit |
jshackley/darkstar | scripts/globals/abilities/pets/healing_breath_ii.lua | 18 | 1467 | ---------------------------------------------------
-- Healing Breath II
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
-- TODO:
-- Healing Breath I and II should have lower multipliers. They'll need to be corrected if the multipliers are ever found. Don't want to over-correct right now.
---------- Deep Breathing ----------
-- 0 for none
-- 50 for first merit
-- 5 for each merit after the first
-- TODO: 5 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 0;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = 50 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*5;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH); -- Master gear that enhances breath
local tp = math.floor(skill:getTP()/20)/1.165; -- HP only increases for every 20% TP
local base = math.floor(((45+tp+gear+deep)/256)*(pet:getMaxHP())+42);
if (target:getHP()+base > target:getMaxHP()) then
base = target:getMaxHP() - target:getHP(); --cap it
end
skill:setMsg(MSG_SELF_HEAL);
target:addHP(base);
return base;
end | gpl-3.0 |
sugiartocokrowibowo/Algorithm-Implementations | Catalan_Numbers/Lua/Yonaba/catalan_test.lua | 26 | 2016 | -- Tests for catalan.lua
local catalan = require 'catalan'
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('10 first Catalan Numbers using direct formula', function()
assert(catalan.direct(0) == 1)
assert(catalan.direct(1) == 1)
assert(catalan.direct(2) == 2)
assert(catalan.direct(3) == 5)
assert(catalan.direct(4) == 14)
assert(catalan.direct(5) == 42)
assert(catalan.direct(6) == 132)
assert(catalan.direct(7) == 429)
assert(catalan.direct(8) == 1430)
assert(catalan.direct(9) == 4862)
assert(catalan.direct(10) == 16796)
end)
run('10 first Catalan Numbers using recursive formula', function()
assert(catalan.recursive(0) == 1)
assert(catalan.recursive(1) == 1)
assert(catalan.recursive(2) == 2)
assert(catalan.recursive(3) == 5)
assert(catalan.recursive(4) == 14)
assert(catalan.recursive(5) == 42)
assert(catalan.recursive(6) == 132)
assert(catalan.recursive(7) == 429)
assert(catalan.recursive(8) == 1430)
assert(catalan.recursive(9) == 4862)
assert(catalan.recursive(10) == 16796)
end)
run('10 first Catalan Numbers using recursive formula', function()
assert(catalan.memoized(0) == 1)
assert(catalan.memoized(1) == 1)
assert(catalan.memoized(2) == 2)
assert(catalan.memoized(3) == 5)
assert(catalan.memoized(4) == 14)
assert(catalan.memoized(5) == 42)
assert(catalan.memoized(6) == 132)
assert(catalan.memoized(7) == 429)
assert(catalan.memoized(8) == 1430)
assert(catalan.memoized(9) == 4862)
assert(catalan.memoized(10) == 16796)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
LiberatorUSA/GUCEF | projects/premake5/targets/GUCEF_exe_UdpViaTcp/premake5.lua | 1 | 1113 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
workspace( "GUCEF_exe_UdpViaTcp" )
platforms( { "ALL" } )
location( "projects\premake5\targets" )
--
-- Includes for all modules in the solution:
--
filter "ALL"
include( "dependencies/json-builder" )
include( "dependencies/json-parser" )
include( "dependencies/libparsifal" )
include( "platform/gucefCOM" )
include( "platform/gucefCOMCORE" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "platform/gucefWEB" )
include( "plugins/CORE/dstorepluginJSONPARSER" )
include( "plugins/CORE/dstorepluginPARSIFALXML" )
include( "tools/UdpViaTcp" )
| apache-2.0 |
jshackley/darkstar | scripts/globals/items/bowl_of_brain_stew.lua | 35 | 1482 | -----------------------------------------
-- ID: 4542
-- Item: Bowl of Brain Stew
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Dexterity 5
-- Intelligence 5
-- Mind 5
-- Health Regen While Healing 3
-- Magic Regen While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4542);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 5);
target:addMod(MOD_INT, 5);
target:addMod(MOD_MND, 5);
target:addMod(MOD_HPHEAL, 3);
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 5);
target:delMod(MOD_INT, 5);
target:delMod(MOD_MND, 5);
target:delMod(MOD_HPHEAL, 3);
target:delMod(MOD_MPHEAL, 3);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Thadiene.lua | 34 | 1983 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Thadiene
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ASH_THADI_ENE_SHOP_DIALOG);
local stock = {0x4380,1575,1, --Boomerang
0x430a,19630,1, --Great Bow
--0x43a9,16,1, --Silver Arrow
0x4302,7128,1, --Wrapped Bow
0x43b8,5,2, --Crossbow Bolt
0x43aa,126,2, --Fire Arrow
0x43a8,7,2, --Iron Arrow
0x4301,482,2, --Self Bow
0x4308,442,3, --Longbow
0x4300,38,3, --Shortbow
0x43a6,3,3, --Wooden Arrow
0x13a5,4320,3} --Scroll of Battlefield Elegy
showNationShop(player, SANDORIA, 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 |
jshackley/darkstar | scripts/zones/Konschtat_Highlands/npcs/qm2.lua | 19 | 1423 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: qm2 (???)
-- Involved in Quest: Forge Your Destiny
-- @pos -709 2 102 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED) then
if (trade:getItemCount() == 1 and trade:hasItemQty(1151,1) and GetMobAction(17219999) == 0) then -- Oriental Steel
SpawnMob(17219999, 300):updateClaim(player); -- Spawn Forger, Despawn after inactive for 5 minutes
player:tradeComplete();
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Titus.lua | 56 | 1742 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Titus
-- Alchemy Synthesis Image Support
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillCap = getCraftSkillCap(player,SKILL_ALCHEMY);
local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then
player:startEvent(0x007B,SkillCap,SkillLevel,1,137,player:getGil(),0,0,0);
else
player:startEvent(0x007B,SkillCap,SkillLevel,1,137,player:getGil(),6758,0,0);
end
else
player:startEvent(0x007B);
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 == 0x007B and option == 1) then
player:messageSpecial(ALCHEMY_SUPPORT,0,7,1);
player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
lpiob/MTA-TokyoRPG | gamemode/RL_VEHICLES_SHOP/vehicles_s.lua | 1 | 7304 | function isPlayerInACL ( player, acl )
local account = getPlayerAccount ( player )
if ( isGuestAccount ( account ) ) then
return false
end
return isObjectInACLGroup ( "user."..getAccountName ( account ), aclGetGroup ( acl ) )
end
function give(playerSource,pcar,car,cost,km)
if isPlayerInACL(playerSource,"Admin") then
if ( car ) then
if not tonumber(car) then
car = string.lower(car)
car = getVehicleModelFromName(car)
end -- w innym przypadku zmienna car nadal będzie przechowywała ID pojazdu, więc nic nie robimy w przypadku gd y podano ID.
x, y, z = getElementPosition(playerSource)
local theCar = createVehicle(car,x,y,z+0.15)
setElementPosition(playerSource,x,y,z+1.5)
local xr,yr,zr = getElementRotation(playerSource)
setElementRotation(theCar,xr,yr,zr)
setElementData(theCar,"vehicle:cost",tonumber(cost))
setElementData(theCar,"vehicle:owner", false)
setElementFrozen(theCar,true)
o utputChatBox("#63DBFF*Stworzyłeś pojazd #B9F46C"..getVehicleNameFromModel(car).." #63DBFFktóry kosztuje #B9F46C"..cost.."$#63DBFF.",playerSource,0,0,0,true)
if km then
setElementData(theCar,"vehicle:travel",tonumber(km))
end
else
outputChatBox("#63DBFF*Wpisałeś złą nazwę auta.",playerSource,0,0,0,true)
end
end
end
addCommandHandler("pcar",give)
function onBuyCar(sPlayer)
if not isGuestAccount(getPlayerAccount(sPlayer)) then
if isPedInVehicle(sPlayer) then
if getElementData(getPedOccupiedVehicle(sPlayer),"vehicle:owner") == false then
if getPlayerMoney(sPlayer)>=tonumber(getElementData(getPedOccupiedVehicle(sPlayer),"vehicle:cost")) then
setElementData(getPedOccupiedVehicle(sPlayer),"vehicle:owner",getPlayerAccount(sPlayer))
setElementData(getPedOccupiedVehicle(sPlayer),"ownername",getPlayerName(sPlayer))
takePlayerMoney(sPlayer,getElementData(getPedOccupiedVehicle(sPlayer),"vehicle:cost"))
setVehicleEngineState(getPedOccupiedVehicle(sPlayer),true)
setElementFrozen(getPedOccupiedVehicle(sPlayer),false)
setElementData(getPedOccupiedVehicle(sPlayer),"ownername",getPlayerName(sPlayer))
outputChatBox("#63DBFF*Kupiłeś/aś pojazd #B9F46C"..getVehicleName(getPedOccupiedVehicle(sPlayer)).."#63DBFF za #B9F46C"..getElementData(getPedOccupiedVehicle(sPlayer),"vehicle:cost").."$#63DBFF.",sPlayer,0,0,0,true)
local x, y, z = getElementPosition(getPedOccupiedVehicle(sPlayer))
local blip = createBlip(x,y,z,0,1,0,0,255,255,0,65535,sPlayer) setElementData(blip,"blip:vehicle",getPedOccupiedVehicle(sPlayer))
else
outputChatBox("#63DBFF*Nie masz wystarczająco dużo pieniędzy żeby kupić ten pojazd.",sPlayer,0,0,0,true)
end
end
else
outputChatBox("#63DBFF*Musisz być zalogowany.",sPlayer,0,0,0,true)
end
end
end
addCommandHandler("kuppojazd",onBuyCar)
function onEnterCar(thePlayer,seat,jacked)
if seat == 0 then
if getElementData(source,"vehicle:owner") == false then
setVehicleEngineState(source,false)
outputChatBox("#63DBFF*Ten pojazd #B9F46C("..getVehicleName(source)..") #63DBFFkosztuje#B9F46C "..getElementData(source,"vehicle:cost").."$#63DBFF.",thePlayer,0,0,0,true)
outputChatBox("#63DBFF*Jeżeli chcesz kupić ten pojazd wpisz#B9F46C /kuppojazd".."#63DBFF.",thePlayer,0,0,0,true)
elseif seat == 0 then
if getElementData(source,"vehicle:owner") then
if getElementData(source,"vehicle:owner") ~= getPlayerAccount(thePlayer)then
removePedFromVehicle(thePlayer)
outputChatBox("#63DBFF*Ten pojazd #B9F46C("..getVehicleName(source)..") #63DBFFnie należy do ciebie.",thePlayer,0,0,0,true)
end
end
end
end
end
addEventHandler("onVehicleStartEnter",getRootElement(),
function (thePlayer,seat,jacked)
if seat == 0 then
if getElementData(source,"vehicle:owner") =~ getPlayerAccount(source) or getElementData(source, "vehicle:owner") == false then
outputChatBox("#63DBFF*Ten pojazd #B9F46C("..getVehicleName(source)..") #63DBFFnie należy do ciebie.",thePlayer,0,0,0,true)
end
end
end
)
addEventHandler("onVehicleEnter",getRootElement(),onEnterCar)
-- Tutaj bylo odswiezanie blipow ale wywalilem to i same blipy bo bylo to nieoptymalne
function sellCar(pps,command,koszt)
if isPedInVehicle(pps) then
if getElementData(getPedOccupiedVehicle(pps),"vehicle:owner") == getPlayerAccount(pps) then
if koszt then
if getElementData(getPedOccupiedVehicle(pps),"vehicle:cost")>=tonumber(koszt) then
setElementData(getPedOccupiedVehicle(pps),"vehicle:cost",tonumber(koszt))
carx = getPedOccupiedVehicle(pps)
setElementFrozen(carx,true)
setVehicleEngineState(carx,false)
setVehicleDamageProof(carx,true)
setElementData(carx,"vehicle:owner", false)
setElementData(carx,"vehicle:used",true)
setElementData(carx,"vehicle:cost",tonumber(koszt))
givePlayerMoney(pps,tonumber(koszt))
outputChatBox("#63DBFF*Wystawiłeś/aś pojazd #B9F46C"..getVehicleName(carx).." #63DBFFza #B9F46C"..tostring(koszt).."$#63DBFF.",pps,0,0,0,true)
removePedFromVehicle(pps)
else
carx = getPedOccupiedVehicle(pps)
outputChatBox("#63DBFF*Nie możesz wystawić tego pojazdu za #B9F46C"..tostring(koszt).."$ #63DBFFponieważ jest to więcej niż jego poprzednia cena #B9F46C("..tostring(getElementData(carx,"vehicle:cost")).."$)#63DBFF.",pps,0,0,0,true)
end
else
outputChatBox("#63DBFF*Żle wpisana komenda powinno być #B9F46C/sprzedajpojazd <cena>#63DBFF.",pps,0,0,0,true)
end
else
outputChatBox("#63DBFF*Ten pojazd nie należy do ciebie.",pps,0,0,0,true)
end
end
end
addCommandHandler("sprzedajpojazd",sellCar)
addEventHandler("onElementDestroy",getRootElement(),function ()
if getElementType(source) = ="vehicle" then
setElementData(source,"vehicle:owner",nil)
setElementData(source,"vehicle:cost",nil)
setElementData(source,"vehicle:used",nil)
setElementData(source,"vehicle:travel",nil)
if getElementData(source,"vehicle:blip") ~= nil or getElementData(source,"vehicle:blip") =~ false then
destroyElement(getElementData(source,"vehicle:blip"))
end
end
end)
setTimer(function ()
for k, v in ipairs(getElementsByType("player")) do
for key, value in ipairs(getElementsByType("blip")) do
if getElementData(value,"blip:vehicle") then
if isElement(getElementData(value,"blip:vehicle")) then
if getElementType(getElementData(value,"blip:vehicle"))=="vehicle" then
local vehicle = getElementData(value,"blip:vehicle")
if getElementData(vehicle,"vehicle:owner")~=0 then
if getElementData(vehicle,"vehicle:owner") == getPlayerAccount(v) then
setElementVisibleTo(value,v,true)
else
setElementVisibleTo(value,v,false)
end
end
end
end
end
end
end
end,1000,0)
| gpl-2.0 |
wfxiang08/thrift | lib/lua/Thrift.lua | 74 | 6739 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
---- namespace thrift
--thrift = {}
--setmetatable(thrift, {__index = _G}) --> perf hit for accessing global methods
--setfenv(1, thrift)
package.cpath = package.cpath .. ';bin/?.so' -- TODO FIX
function ttype(obj)
if type(obj) == 'table' and
obj.__type and
type(obj.__type) == 'string' then
return obj.__type
end
return type(obj)
end
function terror(e)
if e and e.__tostring then
error(e:__tostring())
return
end
error(e)
end
function ttable_size(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
version = 1.0
TType = {
STOP = 0,
VOID = 1,
BOOL = 2,
BYTE = 3,
I08 = 3,
DOUBLE = 4,
I16 = 6,
I32 = 8,
I64 = 10,
STRING = 11,
UTF7 = 11,
STRUCT = 12,
MAP = 13,
SET = 14,
LIST = 15,
UTF8 = 16,
UTF16 = 17
}
TMessageType = {
CALL = 1,
REPLY = 2,
EXCEPTION = 3,
ONEWAY = 4
}
-- Recursive __index function to achieve inheritance
function __tobj_index(self, key)
local v = rawget(self, key)
if v ~= nil then
return v
end
local p = rawget(self, '__parent')
if p then
return __tobj_index(p, key)
end
return nil
end
-- Basic Thrift-Lua Object
__TObject = {
__type = '__TObject',
__mt = {
__index = __tobj_index
}
}
function __TObject:new(init_obj)
local obj = {}
if ttype(obj) == 'table' then
obj = init_obj
end
-- Use the __parent key and the __index function to achieve inheritance
obj.__parent = self
setmetatable(obj, __TObject.__mt)
return obj
end
-- Return a string representation of any lua variable
function thrift_print_r(t)
local ret = ''
local ltype = type(t)
if (ltype == 'table') then
ret = ret .. '{ '
for key,value in pairs(t) do
ret = ret .. tostring(key) .. '=' .. thrift_print_r(value) .. ' '
end
ret = ret .. '}'
elseif ltype == 'string' then
ret = ret .. "'" .. tostring(t) .. "'"
else
ret = ret .. tostring(t)
end
return ret
end
-- Basic Exception
TException = __TObject:new{
message,
errorCode,
__type = 'TException'
}
function TException:__tostring()
if self.message then
return string.format('%s: %s', self.__type, self.message)
else
local message
if self.errorCode and self.__errorCodeToString then
message = string.format('%d: %s', self.errorCode, self:__errorCodeToString())
else
message = thrift_print_r(self)
end
return string.format('%s:%s', self.__type, message)
end
end
TApplicationException = TException:new{
UNKNOWN = 0,
UNKNOWN_METHOD = 1,
INVALID_MESSAGE_TYPE = 2,
WRONG_METHOD_NAME = 3,
BAD_SEQUENCE_ID = 4,
MISSING_RESULT = 5,
INTERNAL_ERROR = 6,
PROTOCOL_ERROR = 7,
INVALID_TRANSFORM = 8,
INVALID_PROTOCOL = 9,
UNSUPPORTED_CLIENT_TYPE = 10,
errorCode = 0,
__type = 'TApplicationException'
}
function TApplicationException:__errorCodeToString()
if self.errorCode == self.UNKNOWN_METHOD then
return 'Unknown method'
elseif self.errorCode == self.INVALID_MESSAGE_TYPE then
return 'Invalid message type'
elseif self.errorCode == self.WRONG_METHOD_NAME then
return 'Wrong method name'
elseif self.errorCode == self.BAD_SEQUENCE_ID then
return 'Bad sequence ID'
elseif self.errorCode == self.MISSING_RESULT then
return 'Missing result'
elseif self.errorCode == self.INTERNAL_ERROR then
return 'Internal error'
elseif self.errorCode == self.PROTOCOL_ERROR then
return 'Protocol error'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_PROTOCOL then
return 'Invalid protocol'
elseif self.errorCode == self.UNSUPPORTED_CLIENT_TYPE then
return 'Unsupported client type'
else
return 'Default (unknown)'
end
end
function TException:read(iprot)
iprot:readStructBegin()
while true do
local fname, ftype, fid = iprot:readFieldBegin()
if ftype == TType.STOP then
break
elseif fid == 1 then
if ftype == TType.STRING then
self.message = iprot:readString()
else
iprot:skip(ftype)
end
elseif fid == 2 then
if ftype == TType.I32 then
self.errorCode = iprot:readI32()
else
iprot:skip(ftype)
end
else
iprot:skip(ftype)
end
iprot:readFieldEnd()
end
iprot:readStructEnd()
end
function TException:write(oprot)
oprot:writeStructBegin('TApplicationException')
if self.message then
oprot:writeFieldBegin('message', TType.STRING, 1)
oprot:writeString(self.message)
oprot:writeFieldEnd()
end
if self.errorCode then
oprot:writeFieldBegin('type', TType.I32, 2)
oprot:writeI32(self.errorCode)
oprot:writeFieldEnd()
end
oprot:writeFieldStop()
oprot:writeStructEnd()
end
-- Basic Client (used in generated lua code)
__TClient = __TObject:new{
__type = '__TClient',
_seqid = 0
}
function __TClient:new(obj)
if ttype(obj) ~= 'table' then
error('TClient must be initialized with a table')
end
-- Set iprot & oprot
if obj.protocol then
obj.iprot = obj.protocol
obj.oprot = obj.protocol
obj.protocol = nil
elseif not obj.iprot then
error('You must provide ' .. ttype(self) .. ' with an iprot')
end
if not obj.oprot then
obj.oprot = obj.iprot
end
return __TObject.new(self, obj)
end
function __TClient:close()
self.iprot.trans:close()
self.oprot.trans:close()
end
-- Basic Processor (used in generated lua code)
__TProcessor = __TObject:new{
__type = '__TProcessor'
}
function __TProcessor:new(obj)
if ttype(obj) ~= 'table' then
error('TProcessor must be initialized with a table')
end
-- Ensure a handler is provided
if not obj.handler then
error('You must provide ' .. ttype(self) .. ' with a handler')
end
return __TObject.new(self, obj)
end
| apache-2.0 |
timse/thrift | lib/lua/Thrift.lua | 74 | 6739 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
---- namespace thrift
--thrift = {}
--setmetatable(thrift, {__index = _G}) --> perf hit for accessing global methods
--setfenv(1, thrift)
package.cpath = package.cpath .. ';bin/?.so' -- TODO FIX
function ttype(obj)
if type(obj) == 'table' and
obj.__type and
type(obj.__type) == 'string' then
return obj.__type
end
return type(obj)
end
function terror(e)
if e and e.__tostring then
error(e:__tostring())
return
end
error(e)
end
function ttable_size(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
version = 1.0
TType = {
STOP = 0,
VOID = 1,
BOOL = 2,
BYTE = 3,
I08 = 3,
DOUBLE = 4,
I16 = 6,
I32 = 8,
I64 = 10,
STRING = 11,
UTF7 = 11,
STRUCT = 12,
MAP = 13,
SET = 14,
LIST = 15,
UTF8 = 16,
UTF16 = 17
}
TMessageType = {
CALL = 1,
REPLY = 2,
EXCEPTION = 3,
ONEWAY = 4
}
-- Recursive __index function to achieve inheritance
function __tobj_index(self, key)
local v = rawget(self, key)
if v ~= nil then
return v
end
local p = rawget(self, '__parent')
if p then
return __tobj_index(p, key)
end
return nil
end
-- Basic Thrift-Lua Object
__TObject = {
__type = '__TObject',
__mt = {
__index = __tobj_index
}
}
function __TObject:new(init_obj)
local obj = {}
if ttype(obj) == 'table' then
obj = init_obj
end
-- Use the __parent key and the __index function to achieve inheritance
obj.__parent = self
setmetatable(obj, __TObject.__mt)
return obj
end
-- Return a string representation of any lua variable
function thrift_print_r(t)
local ret = ''
local ltype = type(t)
if (ltype == 'table') then
ret = ret .. '{ '
for key,value in pairs(t) do
ret = ret .. tostring(key) .. '=' .. thrift_print_r(value) .. ' '
end
ret = ret .. '}'
elseif ltype == 'string' then
ret = ret .. "'" .. tostring(t) .. "'"
else
ret = ret .. tostring(t)
end
return ret
end
-- Basic Exception
TException = __TObject:new{
message,
errorCode,
__type = 'TException'
}
function TException:__tostring()
if self.message then
return string.format('%s: %s', self.__type, self.message)
else
local message
if self.errorCode and self.__errorCodeToString then
message = string.format('%d: %s', self.errorCode, self:__errorCodeToString())
else
message = thrift_print_r(self)
end
return string.format('%s:%s', self.__type, message)
end
end
TApplicationException = TException:new{
UNKNOWN = 0,
UNKNOWN_METHOD = 1,
INVALID_MESSAGE_TYPE = 2,
WRONG_METHOD_NAME = 3,
BAD_SEQUENCE_ID = 4,
MISSING_RESULT = 5,
INTERNAL_ERROR = 6,
PROTOCOL_ERROR = 7,
INVALID_TRANSFORM = 8,
INVALID_PROTOCOL = 9,
UNSUPPORTED_CLIENT_TYPE = 10,
errorCode = 0,
__type = 'TApplicationException'
}
function TApplicationException:__errorCodeToString()
if self.errorCode == self.UNKNOWN_METHOD then
return 'Unknown method'
elseif self.errorCode == self.INVALID_MESSAGE_TYPE then
return 'Invalid message type'
elseif self.errorCode == self.WRONG_METHOD_NAME then
return 'Wrong method name'
elseif self.errorCode == self.BAD_SEQUENCE_ID then
return 'Bad sequence ID'
elseif self.errorCode == self.MISSING_RESULT then
return 'Missing result'
elseif self.errorCode == self.INTERNAL_ERROR then
return 'Internal error'
elseif self.errorCode == self.PROTOCOL_ERROR then
return 'Protocol error'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_PROTOCOL then
return 'Invalid protocol'
elseif self.errorCode == self.UNSUPPORTED_CLIENT_TYPE then
return 'Unsupported client type'
else
return 'Default (unknown)'
end
end
function TException:read(iprot)
iprot:readStructBegin()
while true do
local fname, ftype, fid = iprot:readFieldBegin()
if ftype == TType.STOP then
break
elseif fid == 1 then
if ftype == TType.STRING then
self.message = iprot:readString()
else
iprot:skip(ftype)
end
elseif fid == 2 then
if ftype == TType.I32 then
self.errorCode = iprot:readI32()
else
iprot:skip(ftype)
end
else
iprot:skip(ftype)
end
iprot:readFieldEnd()
end
iprot:readStructEnd()
end
function TException:write(oprot)
oprot:writeStructBegin('TApplicationException')
if self.message then
oprot:writeFieldBegin('message', TType.STRING, 1)
oprot:writeString(self.message)
oprot:writeFieldEnd()
end
if self.errorCode then
oprot:writeFieldBegin('type', TType.I32, 2)
oprot:writeI32(self.errorCode)
oprot:writeFieldEnd()
end
oprot:writeFieldStop()
oprot:writeStructEnd()
end
-- Basic Client (used in generated lua code)
__TClient = __TObject:new{
__type = '__TClient',
_seqid = 0
}
function __TClient:new(obj)
if ttype(obj) ~= 'table' then
error('TClient must be initialized with a table')
end
-- Set iprot & oprot
if obj.protocol then
obj.iprot = obj.protocol
obj.oprot = obj.protocol
obj.protocol = nil
elseif not obj.iprot then
error('You must provide ' .. ttype(self) .. ' with an iprot')
end
if not obj.oprot then
obj.oprot = obj.iprot
end
return __TObject.new(self, obj)
end
function __TClient:close()
self.iprot.trans:close()
self.oprot.trans:close()
end
-- Basic Processor (used in generated lua code)
__TProcessor = __TObject:new{
__type = '__TProcessor'
}
function __TProcessor:new(obj)
if ttype(obj) ~= 'table' then
error('TProcessor must be initialized with a table')
end
-- Ensure a handler is provided
if not obj.handler then
error('You must provide ' .. ttype(self) .. ' with a handler')
end
return __TObject.new(self, obj)
end
| apache-2.0 |
Ombridride/minetest-minetestforfun-server | mods/mobs/mff_menu.lua | 7 | 1637 | --Menu mobs spawner
mobs.shown_spawner_menu = function(player_name)
local formspec = {"size[8,9]label[2.7,0;Mobs Spawner]"}
if mobs["spawning_mobs"] ~= nil then
local Y = 1
local X = 1
for name, etat in pairs(mobs["spawning_mobs"]) do
table.insert(formspec, "item_image_button["..X..","..Y..";1,1;"..name..";"..name..";]")
X = X+1
if X > 6 then
X = 1
Y = Y+1.2
end
end
end
table.insert(formspec, "button_exit[3.9,8.5;1.2,1;close;Close]")
minetest.show_formspec(player_name, "mobs:spawner", table.concat(formspec))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
local player_name = player:get_player_name()
if not player_name then return end
if formname == "mobs:spawner" then
for f in pairs(fields) do
if string.find(f, "mobs:") then
local pos = player:getpos()
pos.y = pos.y+1
minetest.add_entity(pos, f)
return
end
end
end
end)
if (minetest.get_modpath("unified_inventory")) ~= nil then
unified_inventory.register_button("menu_mobs", {
type = "image",
image = "mobs_dungeon_master_fireball.png",
tooltip = "Mobs Spawner Menu",
show_with = "server",
action = function(player)
local player_name = player:get_player_name()
if not player_name then return end
if minetest.check_player_privs(player_name, {server=true}) then
mobs.shown_spawner_menu(player_name)
end
end,
})
else
minetest.register_chatcommand("mobs_spawner", {
params = "",
description = "Spawn entity at given (or your) position",
privs = {server=true},
func = function(name, param)
mobs.shown_spawner_menu(name)
end,
})
end
| unlicense |
PUMpITapp/getsmart | src/newProfile.lua | 1 | 5079 | --- NewProfile
--
-- The new profile function for the app GetSmart
--
require "runState"
--- Checks if the file was called from a test file.
-- @return True or false depending on testing file
function checkTestMode()
--[[runFile = debug.getinfo(2, "S").source:sub(2,3)
if (runFile ~= './' ) then
underGoingTest = false
elseif (runFile == './') then
underGoingTest = true
end
--]]
underGoingTest = false
return underGoingTest
end
--- Chooses either the actual or the stubs depending on if a test file started the program.
-- @param underGoingTest Undergoing test is true if a test file started the program.
function setRequire(underGoingTest)
if not underGoingTest then
if not runsOnSTB then
gfx = require "gfx"
end
text = require "write_text"
animation = require "animation"
profileHandler = require "profileHandler"
elseif underGoingTest then
gfx = require "gfx_stub"
text = require "write_text_stub"
animation = require "animation_stub"
profileHandler = require "profileHandler_stub"
end
return underGoingTest
end
local underGoingTest = setRequire(checkTestMode())
--[[if not runsOnSTB then
dir = ""
else
dir = sys.root_path()
end --]]
-- Imports and sets background
--local background = gfx.loadpng('./images/background.png')
--gfx.screen:copyfrom(background, nil, {x=0 , y=0, w=gfx.screen:get_width(), h=gfx.screen:get_height()})
--gfx.screen:clear({122,219,228})
local background = gfx.loadpng('images/background.png')
gfx.screen:copyfrom(background, nil, {x=0 , y=0, w=gfx.screen:get_width(), h=gfx.screen:get_height()})
background:destroy()
--gfx.update()
-- Requires profiles which is a file containing all profiles and it's related variables and tables
require "profiles"
profilePlayer = ...
-- Test stub to make testing possible
function testGoingToMenu(goingToMenu)
if(underGoingTest and goingToMenu) then
profilePlayer = 'player,1'
elseif(underGoingTest and not goingToMenu) then
profilePlayer = 1
end
end
-- Player variables
name = ''
number = ''
-- All main menu items as .png pictures as transparent background with width and height variables
local png_profile_circle_width = 149
local png_profile_circle_height = 147
local png_profile_circles = { profile1_inactive = 'images/profile/red-inactive.png',
profile1_active = 'images/profile/red-active.png',
profile2_inactive = 'images/profile/green-inactive.png',
profile2_active = 'images/profile/green-active.png',
profile3_inactive = 'images/profile/yellow-inactive.png',
profile3_active = 'images/profile/yellow-active.png',
profile4_inactive = 'images/profile/blue-inactive.png',
profile4_active = 'images/profile/blue-active.png'
}
-- Logotype as .png picture with transparent background with width variable
local png_logo_width = 447
local png_logo = 'images/logo.png'
if not runsOnSTB then
dir = ""
else
dir = sys.root_path()
end
--- Decides if player is sent to keyboard or menu
-- @return If it's a new player (coming from keyboard) return true
function isNewPlayer()
if(tonumber(profilePlayer) == nil) then -- If name (coming from Keyboard)
name, number = profilePlayer:match("([^,]+),([^,]+)") -- Split string into two variables
if(not underGoingTest) then
profileHandler.setName(tonumber(number), tostring(name))
assert(loadfile(dir .. 'menu.lua'))(number)
end
else -- If number (coming from Login)
return true
end
end
--- Prints the number of the player at center of screen
function printPlayerNumber()
if(not tonumber(profilePlayer == nil)) then
local fh = text.getFontHeight('lato', 'large')
local fw = text.getStringLength('lato', 'large', tostring('Player '..profilePlayer))
text.print(gfx.screen, 'lato', 'black', 'large', tostring("Player "..profilePlayer), (gfx.screen:get_width()/2 - (fw/2)), (gfx.screen:get_height()*0.05), fw, fh)
end
end
--- Gets input from user, must be included for input to work
-- @param key The key that has been pressed
-- @param state The state of the key-press
function onKey(key, state)
if state == 'down' then
elseif state == 'up' then
if(key == 'red') then
-- Do nothing
elseif(key == 'green') then
-- Do nothing
elseif(key == 'yellow') then
-- Do nothing
elseif(key == 'blue') then
-- Do nothing
end
end
end
-- Main function that runs the program
local function main()
if(isNewPlayer()) then
printPlayerNumber()
gfx.update()
if(not underGoingTest) then
foo = 0
assert(loadfile(dir .. 'keyboard.lua'))(profilePlayer)
end
end
end
main()
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Mhaura/npcs/Felisa.lua | 17 | 1201 | -----------------------------------
-- Area: Mhaura
-- NPC: Felisa
-- Admits players to the dock in Mhaura.
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() > 38.5) then
player:startEvent(0x00dd,player:getGil(),100);
else
player:startEvent(0x00eb);
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 == 0x00dd and option == 333) then
player:delGil(100);
end
end; | gpl-3.0 |
lichtl/darkstar | scripts/zones/Southern_San_dOria/npcs/Aubejart.lua | 14 | 1489 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Aubejart
-- General Info NPC
-- @zone 230
-- @pos 3 -2 46
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x246);
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 |
ld-test/haricot | haricot.lua | 2 | 10748 | -- NOTES:
-- `job` format: {id=...,data=...}
--- low level
local default_cfg = function()
return {
max_job_size = 2^16,
}
end
local is_posint = function(x)
return ( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) )
end
local hyphen = string.byte("-")
local valid_name = function(x)
local n = #x
return (
(type(x) == "string") and
(n > 0) and (n <= 200) and
(x:byte() ~= hyphen) and
x:match("^[%w-_+/;.$()]+$")
)
end
local luasocket_send = function(s, buf)
return s:send(buf)
end
local luasocket_recv = function(s, bytes)
return s:receive(bytes)
end
local luasocket_getline = function(s)
return s:receive("*l")
end
local luasocket_connect = function(server, port)
local s = (require "socket").tcp()
local ok, err = s:connect(server, port)
if ok then return s else return nil, err end
end
local luasocket_close = function(s)
s:close()
end
local luasocket_t = {
send = luasocket_send,
recv = luasocket_recv,
getline = luasocket_getline,
connect = luasocket_connect,
close = luasocket_close,
}
local lsocket_send = function(s, buf)
local c = #buf
while c > 0 do
local _, wsock = s.lsocket.select(nil, {s.s})
assert(wsock[1] == s.s)
local sent, err = s.s:send(buf)
if not sent then return nil, err end
c = c - sent
end
end
local lsocket_recv = function(s, bytes)
local c, r = bytes, {}
while c > 0 do
local rsock = s.lsocket.select({s.s})
assert(rsock[1] == s.s)
local t = s.s:recv(c)
if not t then return nil end
r[#r+1] = t
c = c - #t
end
return table.concat(r)
end
local lsocket_getline = function(s)
local r = {}
while true do
local c = lsocket_recv(s, 1)
if not c then return nil end
if c == '\n' then return table.concat(r) end
if c ~= '\r' then r[#r+1] = c end
end
end
local lsocket_connect = function(server, port)
local r = {lsocket = (require "lsocket")}
local s, err = r.lsocket.connect("tcp", server, port)
if not s then return nil, err end
local _, wsock = r.lsocket.select(nil, {s})
assert(wsock[1] == s)
r.s = s
s, err = r.s:status()
if not s then return nil, err end
return r
end
local lsocket_close = function(s)
s.s:close()
end
local lsocket_t = {
send = lsocket_send,
recv = lsocket_recv,
getline = lsocket_getline,
connect = lsocket_connect,
close = lsocket_close,
}
local ll_recv = function(self, bytes)
assert(is_posint(bytes))
return self.mod.recv(self.cnx, bytes)
end
local ll_send = function(self, buf)
return self.mod.send(self.cnx, buf)
end
local getline = function(self)
if not self.cnx then return "NOT_CONNECTED" end
return self.mod.getline(self.cnx) or "NOT_CONNECTED"
end
local mkcmd = function(cmd, ...)
return table.concat({cmd, ...}, " ") .. "\r\n"
end
local call = function(self, cmd, ...)
if not self.cnx then return "NOT_CONNECTED" end
ll_send(self, mkcmd(cmd, ...))
return getline(self)
end
local recv = function(self, bytes)
if not self.cnx then return nil end
local r = ll_recv(self, bytes + 2)
if r then
return r:sub(1, bytes)
else return nil end
end
local expect_simple = function(res, s)
if res:match(string.format("^%s$", s)) then
return true
else
return false, res
end
end
local expect_int = function(res, s)
local id = tonumber(res:match(string.format("^%s (%%d+)$", s)))
if id then
return true, id
else
return false, res
end
end
local expect_data = function(self, res)
local bytes = tonumber(res:match("^OK (%d+)$"))
if bytes then
local data = recv(self, bytes)
if data then
assert(#data == bytes)
return true, data
else
return false, "NOT_CONNECTED"
end
else
return false, res
end
end
local expect_job_body = function(self, bytes, id)
local data = recv(self, bytes)
if data then
assert(#data == bytes)
return true, {id = id, data = data}
else
return false, "NOT_CONNECTED"
end
end
--- methods
-- connection
local connect = function(self, server, port)
if self.cnx ~= nil then self:disconnect() end
local mod, err
self.cnx, err = self.mod.connect(server, port)
if not self.cnx then return false, err end
return true
end
local disconnect = function(self)
if self.cnx ~= nil then
self:quit()
self.mod.close(self.cnx)
self.cnx = nil
return true
end
return false, "NOT_CONNECTED"
end
-- producer
local put = function(self, pri, delay, ttr, data)
if not self.cnx then return false, "NOT_CONNECTED" end
assert(
is_posint(pri) and (pri < 2^32) and
is_posint(delay) and
is_posint(ttr) and (ttr > 0)
)
local bytes = #data
assert(bytes < self.cfg.max_job_size)
local cmd = mkcmd("put", pri, delay, ttr, bytes) .. data .. "\r\n"
ll_send(self, cmd)
local res = getline(self)
return expect_int(res, "INSERTED")
end
local use = function(self, tube)
assert(valid_name(tube))
local res = call(self, "use", tube)
local ok = res:match("^USING ([%w-_+/;.$()]+)$")
ok = (ok == tube)
if ok then
return true
else
return false, res
end
end
-- consumer
local reserve = function(self)
local res = call(self, "reserve")
local id, bytes = res:match("^RESERVED (%d+) (%d+)$")
if id --[[and bytes]] then
id, bytes = tonumber(id), tonumber(bytes)
return expect_job_body(self, bytes, id)
else
return false, res
end
end
local reserve_with_timeout = function(self, timeout)
assert(is_posint(timeout))
local res = call(self, "reserve-with-timeout", timeout)
local id, bytes = res:match("^RESERVED (%d+) (%d+)$")
if id --[[and bytes]] then
id, bytes = tonumber(id), tonumber(bytes)
return expect_job_body(self, bytes, id)
else
return expect_simple(res, "TIMED_OUT")
end
end
local delete = function(self, id)
assert(is_posint(id))
local res = call(self, "delete", id)
return expect_simple(res, "DELETED")
end
local release = function(self, id, pri, delay)
assert(
is_posint(id) and
is_posint(pri) and (pri < 2^32) and
is_posint(delay)
)
local res = call(self, "release", id, pri, delay)
return(expect_simple(res, "RELEASED"))
end
local bury = function(self, id, pri)
assert(
is_posint(id) and
is_posint(pri) and (pri < 2^32)
)
local res = call(self, "bury", id, pri)
return expect_simple(res, "BURIED")
end
local touch = function(self, id)
assert(is_posint(id))
local res = call(self, "touch", id)
return expect_simple(res, "TOUCHED")
end
local watch = function(self, tube)
assert(valid_name(tube))
local res = call(self, "watch", tube)
return expect_int(res, "WATCHING")
end
local ignore = function(self, tube)
assert(valid_name(tube))
local res = call(self, "ignore", tube)
return expect_int(res, "WATCHING")
end
-- other
local _peek_result = function(self, res) -- private
local id, bytes = res:match("^FOUND (%d+) (%d+)$")
if id --[[and bytes]] then
id, bytes = tonumber(id), tonumber(bytes)
return expect_job_body(self, bytes, id)
else
return expect_simple(res, "NOT_FOUND")
end
end
local peek = function(self, id)
assert(is_posint(id))
local res = call(self, "peek", id)
return _peek_result(self, res)
end
local make_peek = function(state)
return function(self)
local res = call(self, string.format("peek-%s", state))
return _peek_result(self, res)
end
end
local kick = function(self, bound)
assert(is_posint(bound))
local res = call(self, "kick", bound)
return expect_int(res, "KICKED")
end
local kick_job = function(self, id)
assert(is_posint(id))
local res = call(self, "kick-job", id)
return expect_simple(res, "KICKED")
end
local stats_job = function(self, id)
assert(is_posint(id))
local res = call(self, "stats-job", id)
return expect_data(self, res)
end
local stats_tube = function(self, tube)
assert(valid_name(tube))
local res = call(self, "stats-tube", tube)
return expect_data(self, res)
end
local stats = function(self)
local res = call(self, "stats")
return expect_data(self, res)
end
local list_tubes = function(self)
local res = call(self, "list-tubes")
return expect_data(self, res)
end
local list_tube_used = function(self)
local res = call(self, "list-tube-used")
local tube = res:match("^USING ([%w-_+/;.$()]+)$")
if tube then
return true, tube
else
return false, res
end
end
local list_tubes_watched = function(self)
local res = call(self, "list-tubes-watched")
return expect_data(self, res)
end
local quit = function(self)
if not self.cnx then return false, "NOT_CONNECTED" end
ll_send(self, mkcmd("quit"))
return true
end
local pause_tube = function(self, tube, delay)
assert(valid_name(tube) and is_posint(delay))
local res = call(self, "pause-tube", tube, delay)
return expect_simple(res, "PAUSED")
end
--- class
local methods = {
-- connection
connect = connect, -- (server,port) -> ok,[err]
disconnect = disconnect, -- () -> ok,[err]
-- producer
put = put, -- (pri,delay,ttr,data) -> ok,[id|err]
use = use, -- (tube) -> ok,[err]
-- consumer
reserve = reserve, -- () -> ok,[job|err]
reserve_with_timeout = reserve_with_timeout, -- () -> ok,[job|nil|err]
delete = delete, -- (id) -> ok,[err]
release = release, -- (id,pri,delay) -> ok,[err]
bury = bury, -- (id,pri) -> ok,[err]
touch = touch, -- (id) -> ok,[err]
watch = watch, -- (tube) -> ok,[count|err]
ignore = ignore, -- (tube) -> ok,[count|err]
-- other
peek = peek, -- (id) -> ok,[job|nil|err]
peek_ready = make_peek("ready"), -- () -> ok,[job|nil|err]
peek_delayed = make_peek("delayed"), -- () -> ok,[job|nil|err]
peek_buried = make_peek("buried"), -- () -> ok,[job|nil|err]
kick = kick, -- (bound) -> ok,[count|err]
kick_job = kick_job, -- (id) -> ok,[err]
stats_job = stats_job, -- (id) -> ok,[yaml|err]
stats_tube = stats_tube, -- (tube) -> ok,[yaml|err]
stats = stats, -- () -> ok,[yaml|err]
list_tubes = list_tubes, -- () -> ok,[yaml|err]
list_tube_used = list_tube_used, -- () -> ok,[tube|err]
list_tubes_watched = list_tubes_watched, -- () -> ok,[tube|err]
quit = quit, -- () -> ok
pause_tube = pause_tube, -- (tube,delay) -> ok,[err]
}
local new = function(server, port, mod)
if not mod then
if pcall(require, "socket") then
mod = luasocket_t
elseif pcall(require, "lsocket") then
mod = lsocket_t
else
error("could not find luasocket or lsocket")
end
end
local r = {mod = mod, cfg = default_cfg()}
local ok, err = connect(r, server, port)
return setmetatable(r, {__index = methods}), ok, err
end
return {
new = new, -- instance,conn_ok,[err]
mod = {
luasocket = luasocket_t,
lsocket = lsocket_t,
},
}
-- vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : --
| mit |
pnorman/ClearTables | test-util.lua | 2 | 3153 | --[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2015-2016 Paul Norman, MIT license
]]--
require ("util")
print("util.lua tests")
-- deepcompare is used in other tests, so test it first
print("TESTING: deepcompare")
local t1={}
assert(deepcompare(t1, t1), "test failed: deepcompare same table")
assert(deepcompare({}, {}), "test failed: deepcompare empty table")
assert(deepcompare({2}, {2}), "test failed: deepcompare 1 element equal table")
assert(not deepcompare({2}, {3}), "test failed: deepcompare 1 element equal table")
assert(deepcompare({a="foo", b="bar"}, {b="bar", a="foo"}), "test failed: deepcompare 1 element equal table")
assert(not deepcompare({a="foo", b="bar"}, {b="bar", a="baz"}), "test failed: deepcompare 1 element equal table")
assert(deepcompare({{}, {}}, {{}, {}}), "test failed: deepcompare table of empty tables")
assert(not deepcompare({{}, {}}, {{}, {}, {}}), "test failed: deepcompare different table of empty tables")
assert(deepcompare({{a=1, b=2}, {c=3, d=4}}, {{a=1, b=2}, {c=3, d=4}}), "test failed: deepcompare table of tables")
assert(not deepcompare({{a=1, b=2}, {c=3, d=4}}, {{a=1, b=2}, {c=3, d="foo"}}), "test failed: deepcompare table of different tables")
print("TESTING: isset")
assert(isset(nil) == nil, "test failed: nil")
assert(isset('no') == false, "test failed: no")
assert(isset('false') == false, "test failed: false")
assert(isset('yes'), "test failed: yes")
assert(isset('foo'), "test failed: foo")
print("TESTING: yesno")
assert(yesno(nil) == nil, "test failed: yesno(nil) == nil")
assert(yesno('no') == 'false', "test failed: yesno('no') == 'false'")
assert(yesno('false') == 'false', "test failed: yesno('false') == 'false'")
assert(yesno('yes') == 'true', "test failed: yesno('yes') == 'true'")
assert(yesno('foo') == 'true', "test failed: yesno('foo') == 'true'")
print("TESTING: split_list")
assert(split_list(nil) == nil, "test failed: empty")
assert(split_list('1') == '{"1"}', "test failed: single element")
assert(split_list('1;2') == '{"1","2"}', "test failed: multi-element")
assert(split_list('a"b') == '{"a\\"b"}', "test failed: element with quote")
assert(split_list('a\\b') == '{"a\\\\b"}', "test failed: element with backslash")
assert(split_list('a"\195\188b"c') == '{"a\\"\195\188b\\"c"}', "test failed: unicode element with quote")
print("TESTING: hstore")
assert(hstore(nil) == nil, "test failed: nil")
assert(hstore({}) == '', "test failed: empty")
assert(hstore({foo='bar'}) == '"foo"=>"bar"', "test failed: single element")
local h1 = hstore({foo='bar', baz='2'}) -- pairs does not guarantee any order, so we have to check all
assert(h1 == '"foo"=>"bar","baz"=>"2"' or h1 == '"baz"=>"2","foo"=>"bar"', "test failed: two elements")
assert(hstore({['fo"o']='bar'}) == '"fo\\"o"=>"bar"', "test failed: quoted key")
assert(hstore({['fo\\o']='bar'}) == '"fo\\\\o"=>"bar"', "test failed: backslash key")
assert(hstore({foo='ba"r'}) == '"foo"=>"ba\\"r"', "test failed: quoted value")
assert(hstore({foo='ba\\r'}) == '"foo"=>"ba\\\\r"', "test failed: backslash value")
| mit |
lichtl/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Misseulieu.lua | 17 | 1569 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Misseulieu
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MISSEULIEU_SHOP_DIALOG);
stock = {0x3121,2485, -- Brass Harness
0x32b9,1625, -- Holly Clogs
0x37ed,4042200, -- Barone Cosciales (Available after COP Chapter 4 only)
0x3bc9,25210200, -- Barone Gambieras (Available after COP Chapter 4 only)
0x3a00,7276200, -- Barone Manopolas (Available after COP Chapter 4 only)
0x3c1d,8000000, -- Vir Subligar (Available after COP Chapter 4 only)
0x3c1e,8000000} -- Femina Subligar (Available after COP Chapter 4 only)
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 |
rydnr/radare2 | libr/lang/p/radare.lua | 5 | 16275 | --
-- radare lua api
--
-- 2008 pancake <youterm.com>
-- ========== --
-- --
-- Namespaces --
-- --
-- ========== --
Radare = {}
Radare.Analyze = {}
Radare.Print = {}
Radare.Search = {}
Radare.Config = {}
Radare.Code = {}
Radare.Hash = {}
Radare.Debugger = {}
Radare.Write = {}
Radare.Utils = {}
-- ================= --
-- --
-- Namespace aliases --
-- --
-- ================= --
r = Radare
a = Radare.Analyze
p = Radare.Print
cfg = Radare.Config
code = Radare.Code
hash = Radare.Hash
s = Radare.Search
d = Radare.Debugger
w = Radare.Write
u = Radare.Utils
-- ================ --
-- --
-- Helper functions --
-- --
-- ================ --
function help(table)
if table == nil then
print "Use help(Radare), help(Radare.Debugger) or help(Radare.Print)"
print "These namespaces has been aliased as 'r', 'd' and 'p'."
else
for key,val in pairs(table) do print(" "..key) end
end
return 0
end
function list(table)
local i
i = 0
if table == nil then
print "List the contents of a table"
else
--for key,val in pairs(table) do print(" "..key) end
for k,v in pairs(table) do
if v == nil then
print(" "..k) -- XXX crash
else
print(" "..k..": "..v)
-- k('?')
end
i = i + 1
end
end
return n
end
-- join strings from a table
function join(delimiter, list)
local len = getn(list)
if len == 0 then
return ""
end
local string = list[1]
for i = 2, len do
string = string .. delimiter .. list[i]
end
return string
end
-- split a string by a separator
function split(text, sep)
sep = sep or "\n"
text = chomp(text)
local lines = {}
local pos = 1
while true do
local b,e = text:find(sep, pos)
if not b then table.insert(lines, text:sub(pos)) break end
table.insert(lines, text:sub(pos,b-1))
pos = e + 1
end
return lines
end
function chomp(text)
if text == nil then return "" end
return string.gsub(text, "\n$", "")
end
function chop(text)
if text == nil then return "" end
text = string.gsub(text, "\ *$", "")
return string.gsub(text, "^\ *", "")
end
function hexpairs(buf)
for byte=1, #buf, 16 do
local chunk = buf:sub(byte, byte+15)
io.write(string.format('%08X ',byte-1))
chunk:gsub('.', function (c) io.write(string.format('%02X ',string.byte(c))) end)
io.write(string.rep(' ',3*(16-#chunk)))
io.write(' ',chunk:gsub('%c','.'),"\n")
end
end
function hexdump(buf)
for i=1,math.ceil(#buf/16) * 16 do
if (i-1) % 16 == 0 then io.write(string.format('%08X ', i-1)) end
io.write( i > #buf and ' ' or string.format('%02X ', buf:byte(i)) )
if i % 8 == 0 then io.write(' ') end
if i % 16 == 0 then io.write( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end
end
end
-- ==================== --
-- --
-- Radare API functions --
-- --
-- ==================== --
function Radare.get(value)
-- | cut -d ' ' -f 1");
foo = split(
string.gsub(
cmd_str("? "..value),'(0x[^ ])',
function(x)return x end),';')
return tonumber(foo[1])
end
Radare.bytes_help = 'Radare.bytes(addr)\tReturn hexpair string with block_size bytes at [addr]'
function Radare.bytes(addr)
local res = split(Radare.cmd("pX @"..addr), " ")
-- TODO
return res;
end
Radare.cmd_help = 'Radare.cmd(command)\tExecutes a radare command and returns its output'
function Radare.cmd(cmd)
return chomp(cmd_str(cmd))
end
Radare.system_help = 'Radare.system(command)\tExecute an IO system command'
function Radare.system(command)
r.cmd("!!"..command)
-- todo handle errors here
return 0
end
Radare.iosystem_help = 'Radare.iosystem(command)\tExecute an IO system command'
function Radare.iosystem(command)
r.cmd("!"..command)
-- todo handle errors here
return 0
end
function Radare.open(filename)
r.cmd("o "..filename)
-- todo handle errors here
return 0
end
function Radare.attach(pid)
return r.cmd("o pid://"..pid)
end
function Radare.debug(filename)
return r.cmd("o dbg://"..filename)
end
function Radare.seek(offset)
r.cmd("s "..offset)
return 0
end
function Radare.undo_seek()
r.cmd("u")
-- todo handle errors here
return 0
end
function Radare.redo_seek()
r.cmd("uu")
-- todo handle errors here
return 0
end
function Radare.resize(newsize)
r.cmd("r "..newsize)
-- todo handle errors here
return 0
end
function Radare.fortune()
return r.cmd("fortune")
end
function Radare.interpret(file)
-- control block size
r.cmd(". "..file)
return 0
end
function Radare.copy(size,address)
-- control block size
if address == nil then
r.cmd("y "..size)
else
r.cmd("y "..size.." @ "..address)
end
return 0
end
function Radare.paste(address)
-- control block size
if address == nil then
r.cmd("yy ")
else
r.cmd("yy @ "..address)
end
r.cmd("y "..offset)
return 0
end
function Radare.endian(big)
r.cmd("eval cfg.bigendian = "..big)
return 0
end
function Radare.flag(name, address) -- rename to r.set() ?
if address == nil then
r.cmd("f "..name)
else
r.cmd("f "..name.." @ "..address)
end
return 0
end
function Radare.flag_get(name) -- rename to r.get() ?
local foo = str.split(r.cmd("? "..name), " ")
return foo[1]
end
function Radare.flag_remove(name) -- rename to r.remove() ?
r.cmd("f -"..name)
return 0
end
function Radare.flag_rename(oldname, newname)
r.cmd("fr "..oldname.." "..newname)
return 0
end
function Radare.flag_list(filter)
local list = split(r.cmd("f"))
local ret = {}
local i = 1
while list[i] ~= nil do
local foo = split(list[i], " ")
ret[i] = foo[4]
i = i + 1
end
return ret
end
function Radare.eval(key, value)
if value == nil then
return r.cmd("eval "..key)
end
return r.cmd("eval "..key.." = "..value)
end
function Radare.cmp(value, address)
if address == nil then
r.cmd("c "..value)
else
r.cmd("c "..value.." @ "..address)
end
-- parse output and get ret value
return 0
end
function Radare.cmp_file(file, address)
if address == nil then
r.cmd("cf "..file)
else
r.cmd("cf "..file.." @ "..address)
end
-- parse output and get ret value
return 0
end
function Radare.quit()
r.cmd("q");
return 0
end
function Radare.exit()
return r.quit()
end
-- Radare.Analyze
function Radare.Analyze.opcode(addr)
if addr == nil then addr = "" else addr= "@ "..addr end
local res = split(Radare.cmd("ao "..addr),"\n")
local ret = {}
for i = 1, #res do
local line = split(res[i], "=")
ret[chop(line[1])] = chop(line[2])
end
return ret;
end
function Radare.Analyze.block(addr)
if addr == nil then addr = "" else addr= "@ "..addr end
local res = split(Radare.cmd("ab "..addr),"\n")
local ret = {}
for i = 1, #res do
local line = split(res[i], "=")
ret[chop(line[1])] = chop(line[2])
end
return ret;
end
-- Radare.Debugger API
function Radare.Debugger.step(times)
r.cmd("!step "..times);
return Radare.Debugger
end
function Radare.Debugger.attach(pid)
r.cmd("!attach "..pid);
return Radare.Debugger
end
function Radare.Debugger.detach(pid)
r.cmd("!detach")
return Radare.Debugger
end
function Radare.Debugger.jmp(address)
r.cmd("!jmp "..address)
return Radare.Debugger
end
function Radare.Debugger.set(register, value)
r.cmd("!set "..register.." "..value)
return Radare.Debugger
end
function Radare.Debugger.call(address)
r.cmd("!call "..address)
return Radare.Debugger
end
function Radare.Debugger.dump(name)
r.cmd("!dump "..name)
return Radare.Debugger
end
function Radare.Debugger.restore(name)
r.cmd("!restore "..name)
return Radare.Debugger
end
function Radare.Debugger.bp(address)
r.cmd("!bp "..address)
return Radare.Debugger
end
-- print stuff
function Radare.Print.hex(size, address)
if size == nil then size = "" end
if address == nil then
return r.cmd(":pX "..size)
else
return r.cmd(":pX "..size.." @ "..address)
end
end
function Radare.Print.dis(nops, address)
if nops == nil then nops = "" end
if address == nil then
return r.cmd("pd "..nops)
else
return r.cmd("pd "..nops.." @ "..address)
end
end
function Radare.Print.disasm(size, address)
if size == nil then size = "" end
if address == nil then
return r.cmd("pD "..size)
else
return r.cmd("pD "..size.." @ "..address)
end
end
function Radare.Print.bin(size, address) -- size has no sense here
if size == nil then size = "" end
if address == nil then
return r.cmd(":pb "..size)
else
return r.cmd(":pb "..size.." @ "..address)
end
end
function Radare.Print.string(address) -- size has no sense here
if address == nil then
return r.cmd("pz ")
else
return r.cmd("pz @ "..address)
end
end
function Radare.Print.oct(size,address) -- size has no sense here
if size == nil then size = "" end
if address == nil then
return r.cmd(":po "..size)
end
return r.cmd(":po "..size.."@ "..address)
end
-- search stuff
function Radare.Search.parse(string)
local res = split(string,"\n")
local ret = {}
for i = 1, #res do
local line = split(res[i], " ")
ret[i] = line[3]
end
return ret;
end
function Radare.Search.string(string)
return Radare.Search.parse(Radare.cmd("/ "..string))
end
function Radare.Search.hex(string)
return Radare.Search.parse(Radare.cmd("/x "..string))
end
function Radare.Search.replace(hex_search, hex_write, delta)
if delta == nil then
Radare.Config.set("cmd.hit","wx "..hex_write)
else
Radare.Config.set("cmd.hit","wx "..hex_write.." @ +"..delta)
end
return Radare.Search.parse(Radare.cmd("/x "..hex_search))
end
-- write stuff
function Radare.Write.hex(string, address)
if address == nil then
return r.cmd("wx "..string)
else
return r.cmd("wx "..string.." @ "..address)
end
end
function Radare.Write.string(string, address)
if address == nil then
return r.cmd("w ", string)
else
return r.cmd("w "..string.." @ "..address)
end
end
function Radare.Write.wide_string(string, address)
if address == nil then
return r.cmd("ws "..string)
else
return r.cmd("ws "..string.." @ "..address)
end
end
function Radare.asm(string)
return r.cmd("!rasm '".. string.."'")
end
function Radare.Write.asm(string, address)
if address == nil then
return r.cmd("wa ".. string)
else
return r.cmd("wa "..string.." @ "..address)
end
end
function Radare.Write.rscasm(string, address)
if address == nil then
return r.cmd("wA "..string)
else
return r.cmd("wA "..string.." @ "..address)
end
end
function Radare.Write.from_file(filename, address)
if address == nil then
return r.cmd("wf "..filename)
else
return r.cmd("wf "..filename.." @ "..address)
end
end
-- config stuff
-- eval like
function Radare.Config.verbose(level)
Radare.Config.set("asm.syntax","intel")
Radare.Config.set("asm.lines","false")
Radare.Config.set("asm.offset","false")
Radare.Config.set("asm.bytes","false")
Radare.Config.set("asm.flags","false")
Radare.Config.set("asm.split","false")
Radare.Config.set("scr.color","false")
Radare.Config.set("asm.comments","false")
if level >= 1 then
Radare.Config.set("asm.size", "true")
end
if level >= 2 then
Radare.Config.set("asm.offset", "true")
end
if level >= 3 then
Radare.Config.set("asm.lines", "true")
Radare.Config.set("asm.bytes", "true")
Radare.Config.set("asm.split", "true")
Radare.Config.set("asm.flags", "true")
Radare.Config.set("scr.color", "true")
Radare.Config.set("asm.comments","true")
end
end
-- TODO: store/restore eval config
local Radare_Config_storage = {}
function Radare.Config.store()
local lines = split(r.cmd("e"),"\n")
for i = 1, #lines do
local a = split(lines[i],"=")
if a[1] ~= nil then
if a[2] == nil then a[2]="" end
if (string.match(a[1], "file") ~= nil) then
-- ignore
else
-- TODO. should store everything! (but no reopen :O)
if (string.match(a[1], "asm") ~= nil)
or (string.match(a[1], "scr") ~= nil) then
Radare_Config_storage[a[1]] = a[2]
Radare_Config_storage[a[1]] = a[2]
end
end
end
end
end
function Radare.Config.restore()
for a,b in pairs(Radare_Config_storage) do
Radare.Config.set(a,b)
-- print (a.." = "..b)
end
end
function Radare.Config.set(key, val)
r.cmd("eval "..key.."="..val)
return val
end
function Radare.Config.color(value)
r.cmd("eval scr.color ="..value)
return value
end
function Radare.Config.get(key)
return r.cmd("eval "..key)
end
function Radare.Config.limit(sizs)
return r.cmd("eval cfg.limit = "..size)
end
-- crypto stuff
function Radare.Hash.md5(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#md5 "..size) end
return r.cmd("#md5 "..size.."@"..address)
end
function Radare.Hash.crc32(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#crc32 "..size) end
return r.cmd("#crc32 "..size.."@"..address)
end
function Radare.Hash.md4(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#md4 "..size) end
return r.cmd("#md4 "..size.."@"..address)
end
function Radare.Hash.sha1(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#sha1 "..size) end
return r.cmd("#sha1 "..size.."@"..address)
end
function Radare.Hash.sha256(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#sha256 "..size) end
return r.cmd("#sha256 "..size.."@"..address)
end
function Radare.Hash.sha384(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#sha384 "..size) end
return r.cmd("#sha384 "..size.."@"..address)
end
function Radare.Hash.sha512(size, address)
if size == nil then size = "" end
if address == nil then return r.cmd("#sha512 "..size) end
return r.cmd("#sha512 "..size.."@"..address)
end
function Radare.Hash.hash(algo, size, address)
if size == nil then size = "" end
eval("#"..algo.." "..size)
end
function Radare.Hash.sha512(size, address)
return hash("sha512", size, address)
--if size == nil then size = "" end
--if address == nil then return r.cmd("#sha512 "..size) end
--return r.cmd("#sha512 "..size.."@"..address)
end
-- code api
function Radare.Code.comment(offset, message)
-- TODO: if only offset passed, return comment string
r.cmd("CC "..message.." @ "..offset)
return Radare.Code
end
function Radare.Code.code(offset, len)
r.cmd("Cc "..len.." @ "..offset)
return Radare.Code
end
function Radare.Code.data(offset, len)
r.cmd("Cd "..len.." @ "..offset)
return Radare.Code
end
function Radare.Code.string(offset, len)
r.cmd("Cs "..len.." @ "..offset)
return Radare.Code
end
-- change a signal handler of the child process
function Radare.Debugger.signal(signum, sighandler)
r.cmd("!signal "..signum.." "..sighandler)
return Radare.Debugger
end
function Radare.Debugger.bp_remove(address)
r.cmd("!bp -"..address);
return Radare.Debugger
end
function Radare.Debugger.continue(address)
if address == nil then
r.cmd("!cont");
else
r.cmd("!cont "..address);
end
return Radare.Debugger
end
function Radare.Debugger.step(num)
r.cmd("!step "..num)
return Radare.Debugger
end
function Radare.Debugger.step(num)
r.cmd("!step "..num)
return Radare.Debugger
end
function Radare.Debugger.step_over()
r.cmd("!stepo");
return Radare.Debugger
end
function Radare.Debugger.step_until_user_code()
r.cmd("!stepu");
return Radare.Debugger
end
function Radare.Debugger.add_bp(addr)
r.cmd("!bp "..addr)
return Radare.Debugger
end
function Radare.Debugger.remove_bp(addr)
r.cmd("!bp -"..addr)
return Radare.Debugger
end
function Radare.Debugger.alloc(size)
return cmd_str("!alloc "..size)
end
function Radare.Debugger.free(addr) -- rename to dealloc?
return cmd_str("!free "..addr)
end
function Radare.Debugger.dump(dirname)
r.cmd("!dump "..dirname)
return Radare.Debugger
end
function Radare.Debugger.restore(dirname)
r.cmd("!restore "..dirname)
return Radare.Debugger
end
function Radare.Debugger.jump(addr)
r.cmd("!jmp "..addr)
return Radare.Debugger
end
function Radare.Debugger.backtrace()
local res = split(Radare.cmd("!bt"),"\n")
local ret = {}
for i = 1, #res do
local line = split(res[i], " ")
ret[i] = line[2]
end
return ret;
end
print "[radare.lua] Type 'help()' or 'quit' to return to radare shell."
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Port_Bastok/npcs/Synergy_Engineer.lua | 14 | 1051 | -----------------------------------
-- Area: Port Bastok
-- NPC: Synergy Engineer
-- Type: Standard NPC
-- @zone 236
-- @pos 37.700 -0.3 -50.500
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2afa);
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 |
RunAwayDSP/darkstar | scripts/zones/Northern_San_dOria/npcs/Pirvidiauce.lua | 11 | 1367 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Pirvidiauce
-- Conquest depending medicine seller
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
end
end
function onTrigger(player,npc)
local stock =
{
12986, 9180, 1, --Chestnut Sabbots
4128, 4445, 1, --Ether
4112, 837, 1, --Potion
17336, 6, 2, --Crossbow bolt
4151, 720, 2, --Echo Drops
12985, 1462, 2, --Holly Clogs
4148, 284, 3, --Antidote
12984, 111, 3, --Ash Clogs
219, 900, 3, --Ceramic Flowerpot
4150, 2335, 3, --Eye Drops
1774, 1984, 3, --Red Gravel
17318, 3, 3, --Wooden Arrow
2862, 9200, 3, --Kingdom Waystone
}
player:showText(npc, ID.text.PIRVIDIAUCE_SHOP_DIALOG)
dsp.shop.nation(player, stock, dsp.nation.SANDORIA)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/mobskills/soothing_aroma.lua | 12 | 1036 | ---------------------------------------------
-- Soothing Aroma
-- Family: Rafflesia
-- Description: Charms nearby players.
-- Type:
-- Utsusemi/Blink absorb:
-- Range:
-- Notes:
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
if (mob:getHPP() > 50 and mob:getPool() == 3326) then
-- Raskovnik doesn't use this for the 1st half of its HP.
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.CHARM_I
if (not target:isPC()) then
skill:setMsg(dsp.msg.basic.SKILL_MISS)
return typeEffect
end
local msg = MobStatusEffectMove(mob, target, typeEffect, 0, 3, 150)
if (msg == dsp.msg.basic.SKILL_ENFEEB_IS) then
mob:charm(target)
end
skill:setMsg(msg)
return typeEffect
end
| gpl-3.0 |
lichtl/darkstar | scripts/zones/Norg/npcs/Paito-Maito.lua | 15 | 2550 | -----------------------------------
-- Area: Norg
-- NPC: Paito-Maito
-- Standard Info NPC
-----------------------------------
require("scripts/globals/pathfind");
local path = {
-71.189713, -9.413510, 74.024879,
-71.674171, -9.317029, 73.054794,
-72.516525, -9.298064, 72.363213,
-73.432983, -9.220915, 71.773857,
-74.358955, -9.142115, 71.163277,
-75.199585, -9.069098, 70.583145,
-76.184708, -9.006280, 70.261375,
-77.093193, -9.000236, 70.852921,
-77.987053, -9.037421, 71.464264,
-79.008476, -9.123112, 71.825165,
-80.083740, -9.169785, 72.087944,
-79.577698, -9.295252, 73.087708,
-78.816307, -9.365192, 73.861855,
-77.949852, -9.323165, 74.500496,
-76.868950, -9.301287, 74.783707,
-75.754913, -9.294973, 74.927345,
-74.637566, -9.341335, 74.902016,
-73.521400, -9.382154, 74.747322,
-72.420792, -9.415255, 74.426178,
-71.401161, -9.413510, 74.035446,
-70.392426, -9.413510, 73.627884,
-69.237152, -9.413510, 73.155815,
-70.317207, -9.413510, 73.034027,
-71.371315, -9.279585, 72.798569,
-72.378838, -9.306310, 72.392982,
-73.315544, -9.230491, 71.843933,
-74.225883, -9.153550, 71.253113,
-75.120522, -9.076024, 70.638908,
-76.054642, -9.019394, 70.204910,
-76.981323, -8.999838, 70.762978,
-77.856903, -9.024825, 71.403915,
-78.876686, -9.115798, 71.789764,
-79.930756, -9.171277, 72.053635,
-79.572502, -9.295024, 73.087646,
-78.807686, -9.364762, 73.869614,
-77.916420, -9.321617, 74.516357,
-76.824738, -9.300390, 74.790466,
-75.738380, -9.295794, 74.930130,
-74.620911, -9.341956, 74.899994,
-73.493645, -9.382988, 74.739204,
-72.413185, -9.415321, 74.420128,
-71.452393, -9.413510, 74.054657,
-70.487755, -9.413510, 73.666130
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
-- onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x005A);
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
lichtl/darkstar | scripts/globals/spells/bluemagic/eyes_on_me.lua | 31 | 1587 | -----------------------------------------
-- Spell: Eyes On Me
-- Deals dark damage to an enemy
-- Spell cost: 112 MP
-- Monster Type: Demons
-- Spell Type: Magical (Dark)
-- Blue Magic Points: 4
-- Stat Bonus: HP-5, MP+15
-- Level: 61
-- Casting Time: 4.5 seconds
-- Recast Time: 29.25 seconds
-- Magic Bursts on: Compression, Gravitation, Darkness
-- Combos: Magic Attack 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
local multi = 2.625;
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 2.0;
end
params.multiplier = multi;
params.tMultiplier = 1.5;
params.duppercap = 69;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.2;
damage = BlueMagicalSpell(caster, target, spell, params, CHR_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
cracker1375/mr-Error | libs/lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-2.0 |
RunAwayDSP/darkstar | scripts/commands/addweaponskillpoints.lua | 14 | 1753 | ---------------------------------------------------------------------------------------------------
-- func: addWeaponSkillPoints <slot> <points> {player}
-- desc: Adds weapon skill points to an equipped item.
---------------------------------------------------------------------------------------------------
require("scripts/globals/status")
cmdprops =
{
permission = 1,
parameters = "iis"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!addweaponskillpoints <slot> <points> {player} (main=0, sub=1, ranged=2)")
end
function onTrigger(player, slot, points, target)
-- validate slot
if slot < dsp.slot.MAIN or slot > dsp.slot.RANGED then
error(player, "Slot out of range.")
return
end
-- validate points
if points < 0 then
error(player, "Cannot add negative points.")
return
end
-- validate target
if target == nil then
target = player
else
target = GetPlayerByName(target)
if target == nil then
error(player, string.format("Player named '%s' not found!", target))
return
end
end
local item = target:getStorageItem(0, 0, slot)
if item == nil then
local slotname = slot == 0 and 'main' or slot == 1 and 'sub' or slot == 2 and 'ranged'
error(player, string.format('No weapon equipped in %s slot.', slotname))
return
end
-- add weaponskill points
if target:addWeaponSkillPoints(slot, points) then
player:PrintToPlayer(string.format('Added %s weapon skill points to %s.', points, item:getName()))
else
player:PrintToPlayer(string.format("Could not add weapon skill points to %s.", item:getName()))
end
end | gpl-3.0 |
lichtl/darkstar | scripts/globals/spells/absorb-agi.lua | 17 | 1366 | --------------------------------------
-- Spell: Absorb-AGI
-- Steals an enemy's agility.
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_AGI_DOWN) or caster:hasStatusEffect(EFFECT_AGI_BOOST)) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,37,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
spell:setMsg(332);
caster:addStatusEffect(EFFECT_AGI_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains AGI
target:addStatusEffect(EFFECT_AGI_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASBLE); -- target loses AGI
end
end
return EFFECT_AGI_DOWN;
end; | gpl-3.0 |
ld-test/lluv | test/test-fs.lua | 3 | 2855 | local RUN = lunit and function()end or function ()
local res = lunit.run()
if res.errors + res.failed > 0 then
os.exit(-1)
end
return os.exit(0)
end
local lunit = require "lunit"
local TEST_CASE = assert(lunit.TEST_CASE)
local skip = lunit.skip or function() end
local uv = require "lluv"
local path = require "path"
local TEST_FILE = "./test.txt"
local BAD_FILE = "./test.bad"
local TEST_DATA = "0123456789"
local function mkfile(P, data)
P = path.fullpath(P)
path.mkdir(path.dirname(P))
local f, e = io.open(P, "w+b")
if not f then return nil, err end
if data then assert(f:write(data)) end
f:close()
return P
end
local function rmfile(P)
path.remove(P)
end
local select = select
local ENABLE = true
local _ENV = TEST_CASE'fs' if ENABLE then
local it = setmetatable(_ENV or _M, {__call = function(self, describe, fn)
self["test " .. describe] = fn
end})
function setup()
mkfile(TEST_FILE, TEST_DATA)
end
function teardown()
rmfile(TEST_FILE)
end
it("stat sync", function()
local t, err = assert_table(uv.fs_stat(TEST_FILE))
end)
it("stat async", function()
local run_flag = false
assert_true(uv.fs_stat(TEST_FILE, function(...)
run_flag = true
assert_equal(4, select("#", ...))
local loop, err, stat, path = ...
assert_userdata(loop)
assert_nil(err)
assert_table(stat)
assert_string(path)
end))
assert_equal(0, uv.run())
assert_true(run_flag)
end)
it("stat sync bad file", function()
local _, err = assert_nil(uv.fs_stat(BAD_FILE))
end)
it("stat async bad file", function()
local run_flag = false
assert_true(uv.fs_stat(BAD_FILE, function(...)
run_flag = true
assert_equal(2, select("#", ...))
local loop, err = ...
assert_userdata(loop)
assert_not_nil(err)
end))
assert_equal(0, uv.run())
assert_true(run_flag)
end)
it("unlink sync", function()
assert(path.exists(TEST_FILE))
local t, err = assert_string(uv.fs_unlink(TEST_FILE))
assert(not path.exists(TEST_FILE))
end)
it("unlink async", function()
local run_flag = false
assert(path.exists(TEST_FILE))
assert_true(uv.fs_unlink(TEST_FILE, function(...)
run_flag = true
assert_equal(3, select("#", ...))
local loop, err, path = ...
assert_userdata(loop)
assert_nil(err)
assert_string(path)
end))
assert_equal(0, uv.run())
assert_true(run_flag)
assert(not path.exists(TEST_FILE))
end)
it("unlink sync bad file", function()
local _, err = assert_nil(uv.fs_unlink(BAD_FILE))
end)
it("unlink async bad file", function()
local run_flag = false
assert_true(uv.fs_unlink(BAD_FILE, function(...)
run_flag = true
assert_equal(2, select("#", ...))
local loop, err = ...
assert_userdata(loop)
assert_not_nil(err)
end))
assert_equal(0, uv.run())
assert_true(run_flag)
end)
end
RUN()
| mit |
dufferzafar/ShaR | v1.0 B2.lua | 1 | 9029 | Debug.Clear();
Debug.ShowWindow(true);
--[[
this is a table which contains all the alphabets in random order.
Sandeep, one of my friends helped me out with this.
]]--
tbl_SHAR = {"l","y","f","q","o","s","c","b","x","r","d","j","n","e","p","w","a","h","v","k","m","i","u","z","t","g"};
tbl_SHARCAPS = {"L","Y","F","Q","O","S","C","B","X","R","D","J","N","E","P","W","A","H","V","K","M","I","U","Z","T","G"};
--Contains Symbols
tbl_SYMBOLS = {"`","~","!","@","#","$","%","^","&","*","(",")","-","_","=","+","\\","|","[","]","{","}",";",":","'","\"",",","<",".",">","/","?"};
--These tables contain all the alphabets in correct order.
tbl_ALPHA = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
tbl_ALPHACAPS = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
--This one contains numbers in correct order
tbl_NUM = {"0","1","2","3","4","5","6","7","8","9"};
--Contains All typable characters (for Password usage)
tbl_PASS = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","`","~","!","@","#","$","%","^","&","*","(",")","-","_","=","+","\\","|","[","]","{","}",";",":","'","\"",",","<",".",">","/","?"};
--AMS doesn't has any String.IsUpper() or String.IsLower() function so i wrote mine :)
function IsUpper(char)
for a = 1, 26 do
if char == tbl_ALPHACAPS[a] then
return true;
end
end
return false;
end
function IsLower(char)
for b = 1, 26 do
if char == tbl_ALPHA[b] then
return true;
end
end
return false;
end
--It also doesn't has any IsNumber() but I do :)
function IsNumber(char)
for c = 1, 10 do
if char == tbl_NUM[c] then
return true;
end
end
return false;
--type(String.ToNumber(char) == "number") seems to do the same job but it sucks when a " " or "\n" is passed
end
--Neither it has any String.Reverse() function so i had to write mine :}
function Reverse(str)
local len = String.Length(str);
strrev = ""
for d = len, 1, -1 do
lChar = String.Mid(str,d,1)
strrev = strrev..lChar
end
return strrev;
end
--########################## Helper Functions ###########################
function posInPass(str)
for f = 1, 26 do
if str == tbl_Pass[f] then
return f;
end
end
return 0
end
--#######################################################################
function Ravi_Encrypt(string)
local strlen = String.Length(string); --The length of string
local encText = ""; --The encrypted text currently "Nothing"
local pass = Input.GetText("inPass"); --The Passsword
passLen = String.Length(pass); --Length of Password
cp = 0; --Pass Counter
for e = 1, strlen do
posInAlpha = 0; --The position of the character in lowercase alphabets
posInAlphaCaps = 0; --The position of the character in uppercase alphabets
posInString = 0; --The position of the character in the clear text
nChar = String.Mid(string, e, 1); --Get the string character by character
if cp <= passLen then --DO NOT convert these conditions to if..else.. or the results would vary.
cp = cp + 1 ;
end
if cp > passLen then
cp = 1;
end
nPass = String.Mid(pass, cp, 1);
Debug.Print("nPass = "..nPass.."\r\n");
Debug.Print("nChar = "..nChar.."\r\n");
for m = 1, 26 do
if nChar == tbl_ALPHA[m] then
posInAlpha = m; --The actual position in alphabets
break;
end
end
Debug.Print("posInAlpha = "..posInAlpha.."\r\n");
for n = 1, 26 do
if nChar == tbl_ALPHACAPS[n] then
posInAlphaCaps = n;
break;
end
end
Debug.Print("posInAlphaCaps = "..posInAlphaCaps.."\r\n");
posInString = e; --The actual position in the passed string
Debug.Print("posInString = "..posInString.."\r\n");
--[[
this is the main feature of this cipher, An idea of my friend RAVI KUMAR.
So, basically he is the father of this algorithm although he knows nothing about algorithms.
What we do here is add both the positions so as a result we get different encrypted text which varies with the strings.
for e.g.
The encrypted complement of 'a' in strings 'Shadab' and 'Ravi' will vary as in the first string 'a' occurs at
3rd & 5th position while in second string it occurs at 2nd position.
Either one of posInAlpha or posInAlphaCaps will be zero.
]]--
sumOfPos = posInAlpha + posInAlphaCaps + posInString + posInPass(nPass);
Debug.Print("sumOfPos = "..sumOfPos.."\r\n");
--[[
Handle Characters greater than 26
if this is ommited you won't be able to encrypt 'z' as sumOfPos will then be 27 and there is no value corresponding
to it in tbl_SHAR.
Here, a while loop is a better option than an if condition.
]]--
while sumOfPos > 26 do
sumOfPos = sumOfPos - 26;
end
Debug.Print("NewSumOfPos = "..sumOfPos.."\r\n");
if nChar == " " then --Space
encText = encText.." ";
elseif posInAlpha == 0 and posInAlphaCaps == 0 and IsNumber(nChar) == false then --Non-Alphanumeric.
encText = encText..nChar
elseif IsUpper(nChar) then --Uppercase Chars
encText = encText..tbl_SHARCAPS[sumOfPos];
elseif IsLower(nChar) then --Lowercase chars
encText = encText..tbl_SHAR[sumOfPos];
elseif IsNumber(nChar) and CheckBox.GetChecked("encNum") then --Numbers
local num = String.ToNumber(nChar);
encNum = num + posInString;
while encNum > 9 do --Make the number unary i.e 26 becomes 8 (2+6)
local encNumStr = tostring(encNum);
encNum = 0;
for o = 1, String.Length(encNumStr) do
num = String.ToNumber( String.Mid(encNumStr, o, 1) );
encNum = encNum + num;
end
end
encText = encText..encNum;
else
encText = encText..nChar; --Un-Encrypted Text
end
Debug.Print("encText = "..encText.."\r\n\r\n");
end
return encText;
end --End Of FUNCTION
-----------------------------------------------
function Ravi_Decrypt(string)
local strlen = String.Length(string);
local decText = "";
for p = 1, strlen do
posInShar = 0;
posInSharCaps = 0;
posInString = 0;
nChar = String.Mid(string, p, 1);
Debug.Print("nChar = "..nChar.."\r\n");
for q = 1, 26 do
if nChar == tbl_SHAR[q] then
posInShar = q;
break;
end
end
Debug.Print("posInShar = "..posInShar.."\r\n");
for r = 1, 26 do
if nChar == tbl_SHARCAPS[r] then
posInSharCaps = r;
break;
end
end
Debug.Print("posInSharCaps = "..posInSharCaps.."\r\n");
posInString = p;
Debug.Print("posInString = "..posInString.."\r\n");
diffOfPos = posInShar + posInSharCaps - posInString
Debug.Print("diffOfPos = "..diffOfPos.."\r\n");
while diffOfPos < 0 or diffOfPos == 0 do
diffOfPos = diffOfPos + 26;
end
Debug.Print("NewDiffOfPos = "..diffOfPos.."\r\n");
if nChar == " " then
decText = decText.." ";
elseif posInShar == 0 and posInSharCaps == 0 and IsNumber(nChar) == false then --Non-Alphanumeric
decText = decText..nChar
elseif IsUpper(nChar) then --UpperCase Chars
decText = decText..tbl_ALPHACAPS[diffOfPos];
elseif IsLower(nChar) then --LowerCase Chars
decText = decText..tbl_ALPHA[diffOfPos];
elseif IsNumber(nChar) and CheckBox.GetChecked("encNum") then --Numbers
local num = String.ToNumber(nChar);
decNum = num - posInString;
while decNum < 0 or decNum == 0 do
decNum = decNum + 9
end
decText = decText..decNum;
else
decText = decText..nChar; --Un-Encrypted Text
end
Debug.Print("decText = "..decText.."\r\n\r\n");
end
return decText;
end
--################################################################################################################
if Task == "Encrypt" then
local clearText = Input.GetText("clearText");
--Encrypt the text and Set it to the textbox
if CheckBox.GetChecked("strRev") then
Input.SetText("clearText", Reverse(clearText));
Input.SetText("encText", Ravi_Encrypt(Reverse(clearText)));
else
Input.SetText("encText", Ravi_Encrypt(clearText));
end
elseif Task == "Decrypt" then
local clearText = Input.GetText("clearText");
--Decrypt the text and Set it to the textbox
if CheckBox.GetChecked("strRev") then
Input.SetText("encText", Reverse(Ravi_Decrypt(clearText)));
else
Input.SetText("encText", Ravi_Decrypt(clearText));
end
end | unlicense |
Startg/permag | plugins/fun.lua | 1 | 19335 |
--Special Thx To @SuDo_Star CH;@SkyTeaM
--------------------------------
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
--------------------------------
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
--------------------------------
local function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
--------------------------------
local function get_staticmap(area)
local api = base_api .. "/staticmap?"
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale == "locality" then
zoom=8
elseif scale == "country" then
zoom=4
else
zoom = 13
end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~= nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
--------------------------------
local function get_weather(location)
print("Finding weather in ", location)
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد\n____________________'
local conditions = 'شرایط فعلی آب و هوا : '
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'آفتابی☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ابری ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'بارانی ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'طوفانی ☔☔☔☔'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'مه 💨'
end
return temp .. '\n' .. conditions
end
--------------------------------
local function calc(exp)
url = 'http://api.mathjs.org/v1/'
url = url..'?expr='..URL.escape(exp)
b,c = http.request(url)
text = nil
if c == 200 then
text = 'Result = '..b..'\n____________________'..msg_caption
elseif c == 400 then
text = b
else
text = 'Unexpected error\n'
..'Is api.mathjs.org up?'
end
return text
end
--------------------------------
function exi_file(path, suffix)
local files = {}
local pth = tostring(path)
local psv = tostring(suffix)
for k, v in pairs(scandir(pth)) do
if (v:match('.'..psv..'$')) then
table.insert(files, v)
end
end
return files
end
--------------------------------
function file_exi(name, path, suffix)
local fname = tostring(name)
local pth = tostring(path)
local psv = tostring(suffix)
for k,v in pairs(exi_file(pth, psv)) do
if fname == v then
return true
end
end
return false
end
--------------------------------
function run(msg, matches)
local Chash = "cmd_lang:"..msg.to.id
local Clang = redis:get(Chash)
if matches[1]:lower() == "calc" or matches[1] == 'ماشین حساب' and is_mod(msg) then
if msg.to.type == "pv" then
return
end
return calc(matches[2])
end
--------------------------------
if matches[1]:lower() == "praytime" or matches[1] == 'ساعات شرعی' and is_mod(msg) then
if matches[2] then
city = matches[2]
elseif not matches[2] then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = 'شهر: '..city
text = text..'\nاذان صبح: '..data.Fajr
text = text..'\nطلوع آفتاب: '..data.Sunrise
text = text..'\nاذان ظهر: '..data.Dhuhr
text = text..'\nغروب آفتاب: '..data.Sunset
text = text..'\nاذان مغرب: '..data.Maghrib
text = text..'\nعشاء : '..data.Isha
text = text..msg_caption
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if matches[1]:lower() == "tophoto" or matches[1] == 'تبدیل به عکس' and is_mod(msg) and msg.reply_id then
function tophoto(arg, data)
function tophoto_cb(arg,data)
if data.content_.sticker_ then
local file = data.content_.sticker_.sticker_.path_
local secp = tostring(tcpath)..'/data/sticker/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
local sname = string.gsub(name, 'webp', 'jpg')
local pfile = 'data/photos/'..sname
local pasvand = 'webp'
local apath = tostring(tcpath)..'/data/sticker'
if file_exi(tostring(name), tostring(apath), tostring(pasvand)) then
os.rename(file, pfile)
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This sticker does not exist. Send sticker again._'..msg_caption, 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a sticker._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tophoto_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tophoto, nil)
end
--------------------------------
if matches[1]:lower() == "tosticker" or matches[1] == 'تبدیل به استیکر' and is_mod(msg) and msg.reply_id then
function tosticker(arg, data)
function tosticker_cb(arg,data)
if data.content_.ID == 'MessagePhoto' then
file = data.content_.photo_.id_
local pathf = tcpath..'/data/photo/'..file..'_(1).jpg'
local pfile = 'data/photos/'..file..'.webp'
if file_exi(file..'_(1).jpg', tcpath..'/data/photo', 'jpg') then
os.rename(pathf, pfile)
tdcli.sendDocument(msg.chat_id_, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This photo does not exist. Send photo again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a photo._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tosticker_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tosticker, nil)
end
--------------------------------
if matches[1]:lower() == "weather" or matches[1] == 'اب و هوا' and is_mod(msg) then
city = matches[2]
local wtext = get_weather(city)
if not wtext then
wtext = 'مکان وارد شده صحیح نیست'
end
return wtext
end
--------------------------------
if matches[1]:lower() == "time" or matches[1] == 'ساعت' and is_mod(msg) then
local url , res = http.request('http://irapi.ir/time/')
if res ~= 200 then
return "No connection"
end
local colors = {'blue','green','yellow','magenta','Orange','DarkOrange','red'}
local fonts = {'mathbf','mathit','mathfrak','mathrm'}
local jdat = json:decode(url)
local url = 'http://latex.codecogs.com/png.download?'..'\\dpi{600}%20\\huge%20\\'..fonts[math.random(#fonts)]..'{{\\color{'..colors[math.random(#colors)]..'}'..jdat.ENtime..'}}'
local file = download_to_file(url,'time.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if matches[1]:lower() == "voice" or matches[1] == 'تبدیل به صدا' and is_mod(msg) then
local text = matches[2]
textc = text:gsub(' ','.')
if msg.to.type == 'pv' then
return nil
else
local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..textc
local file = download_to_file(url,'BD-Reborn.mp3')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
end
--------------------------------
if matches[1]:lower() == "tr" or matches[1] == 'ترجمه' and is_mod(msg) then
url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3]))
data = json:decode(url)
return 'زبان : '..data.lang..'\nترجمه : '..data.text[1]..'\n____________________'..msg_caption
end
--------------------------------
if (matches[1]:lower() == 'short' and not Clang) or (matches[1]:lower() == 'لینک کوتاه' and Clang) then
if matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = matches[2]
elseif not matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = "https://"..matches[2]
end
local yon = http.request('http://api.yon.ir/?url='..URL.escape(shortlink))
local jdat = json:decode(yon)
local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(shortlink))
local data = json:decode(bitly)
local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(shortlink))
local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(shortlink)..'&format=simple')
local text = ' 🌐لینک اصلی :\n'..check_markdown(data.data.long_url)..'\n\nلینکهای کوتاه شده با 6 سایت کوتاه ساز لینک : \n》کوتاه شده با bitly :\n___________________________\n'..(check_markdown(data.data.url) or '---')..'\n___________________________\n》کوتاه شده با u2s :\n'..(check_markdown(u2s) or '---')..'\n___________________________\n》کوتاه شده با llink : \n'..(check_markdown(llink) or '---')..'\n___________________________\n》لینک کوتاه شده با yon : \nyon.ir/'..(check_markdown(jdat.output) or '---')..'\n____________________'..msg_caption
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if matches[1]:lower() == "sticker" or matches[1] == 'استیکر' and is_mod(msg) then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if matches[1]:lower() == "photo" or matches[1] == 'عکس' and is_mod(msg) then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.jpg')
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if matches[1] == "fun help" and not Clang then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not lang then
helpfun_en = [[
🔘_.دستورات سرگرمی:_
◾️*!time*
◾️*ساعت*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!short* `[link]`
◾️*لینک کوتاه* `[لینک]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!voice* `[text]`
◾️*تبدیل به صدا* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tr* `[lang] [word]`
◾️*ترجمه* `[زبان] [کلمه]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!sticker* `[word]`
◾️*استیکر* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!photo* `[word]`
◾️*عکس* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!calc* `[number]`
◾️*ماشین حساب* `[معادله]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!praytime* `[city]`
◾️*ساعات شرعی* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tosticker* `[reply]`
◾️*تبدیل به استیکر* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tophoto* `[reply]`
◾️*تبدیل به عکس* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!weather* `[city]`
◾️*اب و هوا* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘_You can use_ *[!/#]* _at the beginning of commands._
🌐 @onemizban\_market 🌐 ;)]]
else
helpfun_en = [[
🔘_.دستورات سرگرمی:_
◾️*!time*
◾️*ساعت*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!short* `[link]`
◾️*لینک کوتاه* `[لینک]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!voice* `[text]`
◾️*تبدیل به صدا* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tr* `[lang] [word]`
◾️*ترجمه* `[زبان] [کلمه]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!sticker* `[word]`
◾️*استیکر* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!photo* `[word]`
◾️*عکس* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!calc* `[number]`
◾️*ماشین حساب* `[معادله]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!praytime* `[city]`
◾️*ساعات شرعی* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tosticker* `[reply]`
◾️*تبدیل به استیکر* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tophoto* `[reply]`
◾️*تبدیل به عکس* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!weather* `[city]`
◾️*اب و هوا* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘_You can use_ *[!/#]* _at the beginning of commands._
🌐 @onemizban_market 🌐 ;)]]
end
return helpfun_en
end
if matches[1] == "راهنما فان" and Clang then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not lang then
helpfun_fa = [[
🔘_.دستورات سرگرمی:_
◾️*!time*
◾️*ساعت*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!short* `[link]`
◾️*لینک کوتاه* `[لینک]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!voice* `[text]`
◾️*تبدیل به صدا* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tr* `[lang] [word]`
◾️*ترجمه* `[زبان] [کلمه]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!sticker* `[word]`
◾️*استیکر* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!photo* `[word]`
◾️*عکس* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!calc* `[number]`
◾️*ماشین حساب* `[معادله]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!praytime* `[city]`
◾️*ساعات شرعی* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tosticker* `[reply]`
◾️*تبدیل به استیکر* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tophoto* `[reply]`
◾️*تبدیل به عکس* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!weather* `[city]`
◾️*اب و هوا* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘_You can use_ *[!/#]* _at the beginning of commands._
🌐 @onemizban\_market 🌐 ;)]]
else
helpfun_fa = [[
🔘_.دستورات سرگرمی:_
◾️*!time*
◾️*ساعت*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!short* `[link]`
◾️*لینک کوتاه* `[لینک]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!voice* `[text]`
◾️*تبدیل به صدا* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tr* `[lang] [word]`
◾️*ترجمه* `[زبان] [کلمه]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!sticker* `[word]`
◾️*استیکر* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!photo* `[word]`
◾️*عکس* `[متن]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!calc* `[number]`
◾️*ماشین حساب* `[معادله]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!praytime* `[city]`
◾️*ساعات شرعی* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tosticker* `[reply]`
◾️*تبدیل به استیکر* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!tophoto* `[reply]`
◾️*تبدیل به عکس* `[ریپلی]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◾️*!weather* `[city]`
◾️*اب و هوا* `[شهر]`
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔘_You can use_ *[!/#]* _at the beginning of commands._
🌐 @onemizban\_market 🌐 ;)]]
end
return helpfun_fa
end
end
--------------------------------
return {
patterns = {
"^[#!/](weather) (.*)$",
"^[#!/](calc) (.*)$",
"^[#!/](time)$",
"^[#!/](fun help)$",
"^[#!/](tophoto)$",
"^[#!/](tosticker)$",
"^[#!/](voice) +(.*)$",
"^[#!/]([Pp]raytime) (.*)$",
"^[#!/](praytime)$",
"^[#!/]([Tt]r) ([^%s]+) (.*)$",
"^[#!/]([Ss]hort) (.*)$",
"^[#!/](photo) (.+)$",
"^[#!/](sticker) (.+)$",
"^(اب و هوا) (.*)$",
"^(ماشین حساب) (.*)$",
"^(ساعت)$",
"^(تبدیل به عکس)$",
"^(تبدیل به استیکر)$",
"^(تبدیل به صدا) +(.*)$",
"^(ساعات شرعی) (.*)$",
"^(ساعات شرعی)$",
"^(ترجمه) ([^%s]+) (.*)$",
"^(لینک کوتاه) (.*)$",
"^(راهنما فان)$",
"^(عکس) (.+)$",
"^(استیکر) (.+)$"
},
run = run,
}
--#EDITby @sudo_star:)
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/zones/Western_Adoulin/npcs/Kipligg.lua | 11 | 2005 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Kipligg
-- Type: Standard NPC and Mission NPC,
-- Involved with Missions: '...Into the Fire', 'Done and Delivered'
-- !pos -32 0 22 256
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local SOA_Mission = player:getCurrentMission(SOA);
if (SOA_Mission < dsp.mission.id.soa.LIFE_ON_THE_FRONTIER) then
-- Dialogue prior to joining colonization effort
player:startEvent(571);
elseif (SOA_Mission == dsp.mission.id.soa.INTO_THE_FIRE) then
-- Finishes SOA Mission: '...Into the Fire'
player:startEvent(155);
elseif ((SOA_Mission >= dsp.mission.id.soa.MELVIEN_DE_MALECROIX) and (SOA_Mission <= dsp.mission.id.soa.COURIER_CATASTROPHE)) then
-- Reminds player where to go for SOA Mission: 'Melvien de Malecroix'
player:startEvent(162);
elseif (SOA_Mission == dsp.mission.id.soa.DONE_AND_DELIVERED) then
-- Finishes SOA Mission: 'Done and Delivered'
player:startEvent(157);
elseif (SOA_Mission == dsp.mission.id.soa.MINISTERIAL_WHISPERS) then
-- Reminds player where to go for SOA Mission: 'Ministerial Whispers'
player:startEvent(163);
else
-- Dialogue after joining colonization effort
player:startEvent(589);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 155) then
-- Finishes SOA Mission: '...Into the Fire'
player:completeMission(SOA, dsp.mission.id.soa.INTO_THE_FIRE);
player:addMission(SOA, dsp.mission.id.soa.MELVIEN_DE_MALECROIX);
elseif (csid == 157) then
-- Finishes SOA Mission: 'Done and Delivered'
player:completeMission(SOA, dsp.mission.id.soa.DONE_AND_DELIVERED);
player:addMission(SOA, dsp.mission.id.soa.MINISTERIAL_WHISPERS);
end
end;
| gpl-3.0 |
RunAwayDSP/darkstar | scripts/globals/mobskills/tebbad_wing_air.lua | 11 | 1150 | ---------------------------------------------
-- Tebbad Wing
--
-- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only by Tiamat, Smok and Ildebrann
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() ~= 1) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.PLAGUE
MobStatusEffectMove(mob, target, typeEffect, 10, 0, 120)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,dsp.magic.ele.FIRE,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.FIRE,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.FIRE)
return dmg
end
| gpl-3.0 |
telergybot/5252265 | plugins/all.lua | 1321 | 4661 | 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 get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
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)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
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 or group_link == nil 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 group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup 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\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \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/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..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] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
UB12/powerlife | plugins/all.lua | 1321 | 4661 | 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 get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
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)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
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 or group_link == nil 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 group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup 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\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \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/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..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] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.