repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
Laterus/Darkstar-Linux-Fork | scripts/zones/Southern_San_dOria/npcs/Taumila.lua | 1 | 2261 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Taumila
-- Starts and Finishes Quest: Tiger's Teeth (R)
-- @zone 230
-- @pos -140 -5 -8
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(884,3) and trade:getItemCount() == 3) then
player:startEvent(0x023c);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
tigersTeeth = player:getQuestStatus(SANDORIA,TIGER_S_TEETH);
if(player:getFameLevel(SANDORIA) >= 3 and tigersTeeth == QUEST_AVAILABLE) then
player:startEvent(0x023e);
elseif(tigersTeeth == QUEST_ACCEPTED) then
player:startEvent(0x023f);
elseif(tigersTeeth == QUEST_COMPLETED) then
player:startEvent(0x023d);
else
player:startEvent(0x023b);
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 == 0x023e and option == 0) then
player:addQuest(SANDORIA,TIGER_S_TEETH);
elseif(csid == 0x023c) then
player:tradeComplete();
player:setTitle(FANG_FINDER);
player:addGil(GIL_RATE*2100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100)
if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,TIGER_S_TEETH);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
end; | gpl-3.0 |
vince06fr/prosody-modules | mod_vjud/mod_vjud.lua | 31 | 5885 | local dm_load = require "util.datamanager".load;
local dm_store = require "util.datamanager".store;
local usermanager = require "core.usermanager";
local dataforms_new = require "util.dataforms".new;
local jid_split = require "util.jid".prepped_split;
local vcard = module:require "vcard";
local rawget, rawset = rawget, rawset;
local s_lower = string.lower;
local s_find = string.find;
local st = require "util.stanza";
local template = require "util.template";
local instructions = module:get_option_string("vjud_instructions", "Fill in one or more fields to search for any matching Jabber users.");
local get_reply = template[[
<query xmlns="jabber:iq:search">
<instructions>{instructions}</instructions>
<first/>
<last/>
<nick/>
<email/>
</query>
]].apply({ instructions = instructions });
local item_template = template[[
<item xmlns="jabber:iq:search" jid="{jid}">
<first>{first}</first>
<last>{last}</last>
<nick>{nick}</nick>
<email>{email}</email>
</item>
]];
local search_mode = module:get_option_string("vjud_mode", "opt-in");
local allow_remote = module:get_option_boolean("allow_remote_searches", search_mode ~= "all");
local base_host = module:get_option_string("vjud_search_domain",
module:get_host_type() == "component"
and module.host:gsub("^[^.]+%.","")
or module.host);
module:depends"disco";
if module:get_host_type() == "component" then
module:add_identity("directory", "user", module:get_option_string("name", "User search"));
end
module:add_feature("jabber:iq:search");
local vCard_mt = {
__index = function(t, k)
if type(k) ~= "string" then return nil end
for i=1,#t do
local t_i = rawget(t, i);
if t_i and t_i.name == k then
rawset(t, k, t_i);
return t_i;
end
end
end
};
local function get_user_vcard(user, host)
local vCard = dm_load(user, host or base_host, "vcard");
if vCard then
vCard = st.deserialize(vCard);
vCard = vcard.from_xep54(vCard);
return setmetatable(vCard, vCard_mt);
end
end
local at_host = "@"..base_host;
local users; -- The user iterator
module:hook("iq/host/jabber:iq:search:query", function(event)
local origin, stanza = event.origin, event.stanza;
if not (allow_remote or origin.type == "c2s") then
origin.send(st.error_reply(stanza, "cancel", "not-allowed"))
return true;
end
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):add_child(get_reply));
else -- type == "set"
local query = stanza.tags[1];
local first, last, nick, email =
s_lower(query:get_child_text"first" or ""),
s_lower(query:get_child_text"last" or ""),
s_lower(query:get_child_text"nick" or ""),
s_lower(query:get_child_text"email" or "");
first = #first >= 2 and first;
last = #last >= 2 and last;
nick = #nick >= 2 and nick;
email = #email >= 2 and email;
if not ( first or last or nick or email ) then
origin.send(st.error_reply(stanza, "modify", "not-acceptable", "All fields were empty or too short"));
return true;
end
local reply = st.reply(stanza):query("jabber:iq:search");
local username, hostname = jid_split(email);
if hostname == base_host and username and usermanager.user_exists(username, hostname) then
local vCard = get_user_vcard(username);
if vCard then
reply:add_child(item_template.apply{
jid = username..at_host;
first = vCard.N and vCard.N[2] or nil;
last = vCard.N and vCard.N[1] or nil;
nick = vCard.NICKNAME and vCard.NICKNAME[1] or username;
email = vCard.EMAIL and vCard.EMAIL[1] or nil;
});
end
else
for username in users() do
local vCard = get_user_vcard(username);
if vCard
and ((first and vCard.N and s_find(s_lower(vCard.N[2]), first, nil, true))
or (last and vCard.N and s_find(s_lower(vCard.N[1]), last, nil, true))
or (nick and vCard.NICKNAME and s_find(s_lower(vCard.NICKNAME[1]), nick, nil, true))
or (email and vCard.EMAIL and s_find(s_lower(vCard.EMAIL[1]), email, nil, true))) then
reply:add_child(item_template.apply{
jid = username..at_host;
first = vCard.N and vCard.N[2] or nil;
last = vCard.N and vCard.N[1] or nil;
nick = vCard.NICKNAME and vCard.NICKNAME[1] or username;
email = vCard.EMAIL and vCard.EMAIL[1] or nil;
});
end
end
end
origin.send(reply);
end
return true;
end);
if search_mode == "all" then
function users()
return usermanager.users(base_host);
end
else -- if "opt-in", default
local opted_in;
function module.load()
opted_in = dm_load(nil, module.host, "user_index") or {};
end
function module.unload()
dm_store(nil, module.host, "user_index", opted_in);
end
function users()
return pairs(opted_in);
end
local opt_in_layout = dataforms_new{
title = "Search settings";
instructions = "Do you want to appear in search results?";
{
name = "searchable",
label = "Appear in search results?",
type = "boolean",
},
};
local function opt_in_handler(self, data, state)
local username, hostname = jid_split(data.from);
if state then -- the second return value
if data.action == "cancel" then
return { status = "canceled" };
end
if not username or not hostname or hostname ~= base_host then
return { status = "error", error = { type = "cancel",
condition = "forbidden", message = "Invalid user or hostname." } };
end
local fields = opt_in_layout:data(data.form);
opted_in[username] = fields.searchable or nil
return { status = "completed" }
else -- No state, send the form.
return { status = "executing", actions = { "complete" },
form = { layout = opt_in_layout, values = { searchable = opted_in[username] } } }, true;
end
end
local adhoc_new = module:require "adhoc".new;
local adhoc_vjudsetup = adhoc_new("Search settings", "vjudsetup", opt_in_handler);--, "self");-- and nil);
module:depends"adhoc";
module:provides("adhoc", adhoc_vjudsetup);
end
| mit |
jkassman/wesnoth | data/campaigns/The_Hammer_of_Thursagan/lua/spawns.lua | 27 | 1324 | -- Used for the bandit spawns in scenario 5
local helper = wesnoth.require "lua/helper.lua"
local wml_actions = wesnoth.wml_actions
local T = helper.set_wml_tag_metatable {}
function wml_actions.spawn_units(cfg)
local x = cfg.x or helper.wml_error("[spawn_units] missing required x= attribute.")
local y = cfg.y or helper.wml_error("[spawn_units] missing required y= attribute.")
local types = cfg.types or helper.wml_error("[spawn_units] missing required types= attribute.")
local count = cfg.count or helper.wml_error("[spawn_units] missing required count= attribute.")
local side = cfg.side or helper.wml_error("[spawn_units] missing required side= attribute.")
for i=1,count do
local locs = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = 1 } })
if #locs == 0 then locs = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = 2 } }) end
local unit_type = helper.rand(types)
local loc_i = helper.rand("1.."..#locs)
wml_actions.move_unit_fake({x = string.format("%d,%d", x, locs[loc_i][1]) , y = string.format("%d,%d", y, locs[loc_i][2]) , type = unit_type , side = side})
wesnoth.put_unit(locs[loc_i][1], locs[loc_i][2], { type = unit_type , side = side, random_traits = "yes", generate_name = "yes" , upkeep = "loyal" })
end
end
| gpl-2.0 |
gleachkr/luakit | lib/formfiller_wm.lua | 3 | 9797 | -- Luakit formfiller - web module.
--
-- @submodule formfiller_wm
-- @copyright 2016 Aidan Holm <aidanholm@gmail.com>
local select = require("select_wm")
local lousy = require("lousy")
local ui = ipc_channel("formfiller_wm")
local filter = lousy.util.table.filter_array
local function element_attributes_match(element, attrs)
for attr, value in pairs(attrs) do
if not string.find(value, element.attr[attr] or "", 1, true) then
return false
end
end
return true
end
local function attribute_matches(tag, attrs, parents)
local documents = {}
parents = parents and parents or documents
local elements = {}
for _, parent in ipairs(parents) do
local e = parent:query(tag)
for _, element in ipairs(e) do
if element_attributes_match(element, attrs) then
elements[#elements+1] = element
end
end
end
return elements
end
local function match(tag, attrs, form, parents)
assert(type(parents) == "table")
local attr_table = {}
for _, v in ipairs(attrs) do
if form[v] then
attr_table[v] = form[v]
end
end
local matches = attribute_matches(tag, attr_table, parents)
return matches
end
local function fill_input(inputs, value)
assert(type(inputs) == "table")
for _, input in pairs(inputs) do
assert(type(input) == "dom_element")
if input.type == "radio" or input.type == "checkbox" then
-- Click the input if it isn't already in the desired state
local checked = input.checked == "checked"
if value and value ~= checked then
input:click()
end
else
input.value = value
end
end
end
local function submit_form(form, n)
assert(type(form) == "dom_element" and form.tag_name == "FORM")
assert(type(n) == "number")
local submits = form:query("input[type=submit]")
local submit = submits[n == 0 and 1 or n]
assert(submit)
-- Fall back to clicking if submit input has onclick handler
if n > 0 or submit.attr.onclick then
submit:click()
else
form:submit()
end
end
local function contains(tbl, item)
for _, v in ipairs(tbl) do
if v == item then return true end
end
return false
end
local stylesheet = [===[
#luakit_select_overlay {
position: absolute;
left: 0;
top: 0;
z-index: 2147483647; /* Maximum allowable on WebKit */
}
#luakit_select_overlay .hint_overlay {
display: block;
position: absolute;
background-color: #ffff99;
border: 1px dotted #000;
opacity: 0.3;
}
#luakit_select_overlay .hint_label {
display: block;
position: absolute;
background-color: #000088;
border: 1px dashed #000;
color: #fff;
font-size: 10px;
font-family: monospace, courier, sans-serif;
opacity: 0.4;
}
#luakit_select_overlay .hint_selected {
background-color: #00ff00 !important;
}
]===]
local dsl_coroutines = {}
ui:add_signal("dsl_extension_reply", function(_, _, v, view_id)
coroutine.resume(dsl_coroutines[view_id],v)
end)
local function traverse(view_id, t)
if type(t) == "table" and t.sentinel then
ui:emit_signal("dsl_extension_query", t.key,t.arg,view_id)
return coroutine.yield(dsl_coroutines[view_id])
elseif type(t) == "table" then
for k,v in pairs(t) do t[k] = traverse(view_id, v) end
end
return t
end
local function apply (form, form_spec, page)
local co = coroutine.create(function ()
-- Map of attr -> value that form has to match
local attrs = {}
for _, v in ipairs({"method", "name", "id", "action", "className"}) do
attrs[v] = traverse(page.id, form_spec[v]) -- traverse and evaluate attributes
form_spec[v] = attrs[v] -- write them back to the form_spec
end
if not element_attributes_match(form, attrs) then
return false
end
traverse(page.id, form_spec) -- traverse the rest of the form_spec
for _, input_spec in ipairs(form_spec.inputs) do
local matches = match("input", {"name", "id", "className", "type"}, input_spec, {form})
if #matches > 0 then
local val = input_spec.value or input_spec.checked
if val then fill_input(matches, val) end
if input_spec.focus then matches[1]:focus() end
if input_spec.select then matches[1]:select() end
end
end
if form_spec.submit then
submit_form(form, type(form_spec.submit) == "number" and form_spec.submit or 0)
end
dsl_coroutines[page.id] = nil
return true
end)
dsl_coroutines[page.id] = co
coroutine.resume(co)
end
local function formfiller_fill (page, form, form_specs)
assert(type(page) == "page")
assert(type(form) == "dom_element" and form.tag_name == "FORM")
for _, form_spec in ipairs(form_specs) do
if apply(form, form_spec, page) then
break
end
end
ui:emit_signal("finished")
end
local function get_form_spec_matches_on_page(page, form_specs)
assert(type(page) == "page")
assert(type(form_specs) == "table")
local forms = {}
for _, form_spec in ipairs(form_specs) do
local attrs = {"method", "name", "id", "action", "className"}
local matches = match("form", attrs, form_spec, { page.document.body })
for _, form in ipairs(matches) do
forms[#forms+1] = form
end
end
return forms
end
local function formfiller_fill_fast (page, form_specs)
-- Build list of matchable form elements
local forms = get_form_spec_matches_on_page(page, form_specs)
if #forms == 0 then
ui:emit_signal("failed", page.id, "page has no matchable forms")
return
end
if #forms > 1 then
ui:emit_signal("failed", page.id, "page has more than one matchable form")
return
end
formfiller_fill(page, forms[1], form_specs)
end
local function formfiller_add (page, form)
assert(type(page) == "page")
assert(type(form) == "dom_element" and form.tag_name == "FORM")
local function to_lua_str(str)
return "'" .. str:gsub("([\\'])", "\\%1").. "'"
end
local function to_lua_pat(str)
return to_lua_str(lousy.util.lua_escape(str))
end
local function add_attr(elem, attr, indent, tail)
local a = elem.attr[attr]
if type(a) == "string" and a ~= "" then
return indent .. attr .. " = " .. to_lua_str(a) .. tail
else
return ""
end
end
local inputs = filter(form:query("input"), function(_, input)
return not contains({"button", "submit", "hidden"}, input.type)
end)
-- Build formfiller config for form
local str = { "on " .. to_lua_pat(page.uri) .. " {\n"}
table.insert(str, " form {\n")
for _, attr in ipairs({"method", "action", "id", "className", "name"}) do
table.insert(str, add_attr(form, attr, " ", ",\n"))
end
for _, input in ipairs(inputs) do
table.insert(str, " input {\n ")
for _, attr in ipairs({"id", "className", "name", "type"}) do
table.insert(str, add_attr(input, attr, "", ", "))
end
if contains({"radio", "checkbox"}, input.type) then
table.insert(str, "\n checked = " .. (input.checked or "false") .. ",\n")
else
table.insert(str, "\n value = " .. to_lua_str(input.value or "") .. ",\n")
end
table.insert(str, " },\n")
end
table.insert(str, " submit = true,\n")
table.insert(str, " autofill = true,\n")
table.insert(str, " },\n")
table.insert(str, "}\n\n")
str = table.concat(str)
ui:emit_signal("add", page.id, str)
end
ui:add_signal("fill-fast", function(_, page, form_specs)
formfiller_fill_fast(page, form_specs)
end)
ui:add_signal("apply_form", function(_, page, form)
formfiller_fill_fast(page, {form})
end)
ui:add_signal("leave", function (_, page)
select.leave(page)
end)
ui:add_signal("focus", function (_, page, step)
select.focus(page, step)
end)
-- Visual formfiller add
ui:add_signal("enter", function (_, page)
-- Filter forms to those with valid inputs
local forms = page.document.body:query("form")
forms = filter(forms, function(_, form)
local inputs = form:query("input")
inputs = filter(inputs, function(_, input)
return not contains({"button", "submit", "hidden"}, input.type)
end)
return #inputs > 0
end)
-- Error out if there aren't any forms to add
if #forms == 0 then
ui:emit_signal("failed", page.id, "page has no forms that can be added")
end
select.enter(page, forms, stylesheet, true)
end)
ui:add_signal("changed", function (_, page, text)
local _, num_visible_hints = select.changed(page, "^" .. text, nil, text)
if num_visible_hints == 1 and text ~= "" then
local hint = select.focused_hint(page)
formfiller_add(page, hint.elem)
end
end)
ui:add_signal("select", function (_, page)
local hint = select.focused_hint(page)
formfiller_add(page, hint.elem)
end)
ui:add_signal("filter", function (_, page, form_specs)
local matching_form_specs = {}
local roots = { page.document.body }
for _, form_spec in ipairs(form_specs) do
local matches = match("form", {"method", "name", "id", "action", "className"}, form_spec, roots)
if #matches > 0 then
matching_form_specs[#matching_form_specs+1] = form_spec
end
end
ui:emit_signal("filter", page.id, matching_form_specs)
end)
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
RyMarq/Zero-K | LuaUI/Widgets/gui_chili_resource_bars.lua | 2 | 25472 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Chili Resource Bars Classic",
desc = "",
author = "jK",
date = "2010",
license = "GNU GPL, v2 or later",
layer = 0,
experimental = false,
enabled = false
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("colors.h.lua")
VFS.Include("LuaRules/Configs/constants.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local abs = math.abs
local echo = Spring.Echo
local GetMyTeamID = Spring.GetMyTeamID
local GetTeamResources = Spring.GetTeamResources
local GetTimer = Spring.GetTimer
local DiffTimers = Spring.DiffTimers
local Chili
local spGetTeamRulesParam = Spring.GetTeamRulesParam
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local col_metal = {136/255,214/255,251/255,1}
local col_energy = {1,1,0,1}
local col_buildpower = {0.8, 0.8, 0.2, 1}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local window
local bar_metal
local bar_metal_reserve_overlay
local bar_energy
local bar_energy_overlay
local bar_energy_reserve_overlay
local bar_buildpower
local lbl_metal
local lbl_energy
local lbl_m_expense
local lbl_e_expense
local lbl_m_income
local lbl_e_income
local blink = 0
local blink_periode = 2
local blink_alpha = 1
local blinkM_status = false
local blinkE_status = false
local time_old = 0
local excessE = false
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local builderDefs = {}
for id,ud in pairs(UnitDefs) do
if (ud.isBuilder) then
builderDefs[#builderDefs+1] = id
elseif (ud.buildSpeed > 0) then
builderDefs[#builderDefs+1] = id
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
options_path = 'Settings/HUD Panels/Resource Bars'
local function option_workerUsageUpdate()
DestroyWindow()
CreateWindow()
end
options_order = {'eexcessflashalways', 'energyFlash', 'workerUsage','opacity','onlyShowExpense','enableReserveBar','defaultEnergyReserve','defaultMetalReserve'}
options = {
eexcessflashalways = {name='Always Flash On Energy Excess', type='bool', value=false},
onlyShowExpense = {name='Only Show Expense', type='bool', value=false},
enableReserveBar = {name='Enable Reserve', type='bool', value=false, tooltip = "Enables high priority reserve"},
defaultEnergyReserve = {
name = "Initial Energy Reserve",
type = "number",
value = 0.05, min = 0, max = 1, step = 0.01,
},
defaultMetalReserve = {
name = "Initial Metal Reserve",
type = "number",
value = 0, min = 0, max = 1, step = 0.01,
},
workerUsage = {name = "Show Worker Usage", type = "bool", value=false, OnChange = option_workerUsageUpdate},
energyFlash = {name = "Energy Stall Flash", type = "number", value=0.1, min=0,max=1,step=0.02},
opacity = {
name = "Opacity",
type = "number",
value = 0, min = 0, max = 1, step = 0.01,
OnChange = function(self) window.color = {1,1,1,self.value}; window:Invalidate() end,
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- 1 second lag as energy update will be included in next resource update, not this one
local lastChange = 0
local lastEnergyForOverdrive = 0
local lastEnergyWasted = 0
local lastMetalFromOverdrive = 0
local lastMyMetalFromOverdrive = 0
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local cp = {}
-- note works only in communism mode
function UpdateCustomParamResourceData()
local teamID = Spring.GetLocalTeamID()
cp.allies = spGetTeamRulesParam(teamID, "OD_allies") or 1
cp.team_metalBase = spGetTeamRulesParam(teamID, "OD_team_metalBase") or 0
cp.team_metalOverdrive = spGetTeamRulesParam(teamID, "OD_team_metalOverdrive") or 0
cp.team_metalMisc = spGetTeamRulesParam(teamID, "OD_team_metalMisc") or 0
cp.team_energyIncome = spGetTeamRulesParam(teamID, "OD_team_energyIncome") or 0
cp.team_energyOverdrive = spGetTeamRulesParam(teamID, "OD_team_energyOverdrive") or 0
cp.team_energyWaste = spGetTeamRulesParam(teamID, "OD_team_energyWaste") or 0
cp.metalBase = spGetTeamRulesParam(teamID, "OD_metalBase") or 0
cp.metalOverdrive = spGetTeamRulesParam(teamID, "OD_metalOverdrive") or 0
cp.metalMisc = spGetTeamRulesParam(teamID, "OD_metalMisc") or 0
cp.energyIncome = spGetTeamRulesParam(teamID, "OD_energyIncome") or 0
cp.energyOverdrive = spGetTeamRulesParam(teamID, "OD_energyOverdrive") or 0
cp.energyChange = spGetTeamRulesParam(teamID, "OD_energyChange") or 0
end
local function updateReserveBars(metal, energy, value, overrideOption)
if options.enableReserveBar.value or overrideOption then
if value < 0 then value = 0 end
if value > 1 then value = 1 end
if metal then
local _, mStor = GetTeamResources(GetMyTeamID(), "metal")
Spring.SendLuaRulesMsg("mreserve:"..value*(mStor - HIDDEN_STORAGE))
WG.metalStorageReserve = value*(mStor - HIDDEN_STORAGE)
bar_metal_reserve_overlay:SetValue(value)
end
if energy then
local _, eStor = GetTeamResources(GetMyTeamID(), "energy")
Spring.SendLuaRulesMsg("ereserve:"..value*(eStor - HIDDEN_STORAGE))
WG.energyStorageReserve = value*(eStor - HIDDEN_STORAGE)
bar_energy_reserve_overlay:SetValue(value)
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Update(s)
blink = (blink+s)%blink_periode
blink_alpha = math.abs(blink_periode/2 - blink)
if blinkM_status then
bar_metal:SetColor( 1 - 119/255*blink_alpha,214/255,251/255,0.65 + 0.3*blink_alpha )
end
if blinkE_status then
if excessE then
bar_energy_overlay:SetColor({0,0,0,0})
bar_energy:SetColor(1-0.5*blink_alpha,1,0,0.65 + 0.35 *blink_alpha)
else
-- flash red if stalling
bar_energy_overlay:SetColor(1,0,0,blink_alpha)
end
end
end
local function Format(input, override)
local leadingString = GreenStr .. "+"
if input < 0 then
leadingString = RedStr .. "-"
end
leadingString = override or leadingString
input = math.abs(input)
if input < 0.05 then
return WhiteStr .. "0"
elseif input < 5 then
return leadingString .. ("%.2f"):format(input) .. WhiteStr
elseif input < 50 then
return leadingString .. ("%.1f"):format(input) .. WhiteStr
elseif input < 10^3 then
return leadingString .. ("%.0f"):format(input) .. WhiteStr
elseif input < 10^4 then
return leadingString .. ("%.2f"):format(input/1000) .. "k" .. WhiteStr
elseif input < 10^5 then
return leadingString .. ("%.1f"):format(input/1000) .. "k" .. WhiteStr
else
return leadingString .. ("%.0f"):format(input/1000) .. "k" .. WhiteStr
end
end
local initialReserveSet = false
function widget:GameFrame(n)
if (n%TEAM_SLOWUPDATE_RATE ~= 0) or not window then
return
end
if n > 5 and not initialReserveSet then
updateReserveBars(true, false, options.defaultMetalReserve.value, true)
updateReserveBars(false, true, options.defaultEnergyReserve.value, true)
initialReserveSet = true
end
UpdateCustomParamResourceData()
local myTeamID = GetMyTeamID()
local myAllyTeamID = Spring.GetMyAllyTeamID()
local teams = Spring.GetTeamList(myAllyTeamID)
local totalPull = 0
local teamEnergyExp = 0
local teamMInco = 0
local teamMSpent = 0
local teamMPull = 0
local teamFreeStorage = 0
local teamEnergyReclaim = 0
local teamTotalMetalStored = 0
local teamTotalMetalCapacity = 0
local teamTotalEnergyStored = 0
local teamTotalEnergyCapacity = 0
for i = 1, #teams do
local mCurr, mStor, mPull, mInco, mExpe, mShar, mSent, mReci = GetTeamResources(teams[i], "metal")
teamMInco = teamMInco + mInco
teamMSpent = teamMSpent + mExpe
teamFreeStorage = teamFreeStorage + mStor - mCurr
teamTotalMetalStored = teamTotalMetalStored + math.min(mCurr, mStor - HIDDEN_STORAGE)
teamTotalMetalCapacity = teamTotalMetalCapacity + mStor - HIDDEN_STORAGE
local extraMetalPull = spGetTeamRulesParam(teams[i], "extraMetalPull") or 0
teamMPull = teamMPull + mPull + extraMetalPull
local eCurr, eStor, ePull, eInco, eExpe, eShar, eSent, eReci = GetTeamResources(teams[i], "energy")
local extraEnergyPull = spGetTeamRulesParam(teams[i], "extraEnergyPull") or 0
local energyOverdrive = spGetTeamRulesParam(teams[i], "OD_energyOverdrive") or 0
local energyChange = spGetTeamRulesParam(teams[i], "OD_energyChange") or 0
local extraChange = math.min(0, energyChange) - math.min(0, energyOverdrive)
totalPull = totalPull + ePull + extraEnergyPull + extraChange
teamEnergyExp = teamEnergyExp + eExpe + extraChange
teamEnergyReclaim = teamEnergyReclaim + eInco - math.max(0, energyChange)
teamTotalEnergyStored = teamTotalEnergyStored + math.min(eCurr, eStor - HIDDEN_STORAGE)
teamTotalEnergyCapacity = teamTotalEnergyCapacity + eStor - HIDDEN_STORAGE
end
local teamEnergyIncome = teamEnergyReclaim + cp.team_energyIncome
local eCurr, eStor, ePull, eInco, eExpe, eShar, eSent, eReci = GetTeamResources(myTeamID, "energy")
local mCurr, mStor, mPull, mInco, mExpe, mShar, mSent, mReci = GetTeamResources(myTeamID, "metal")
local eReclaim = eInco
eInco = eInco + cp.energyIncome - math.max(0, cp.energyChange)
totalPull = totalPull - cp.team_energyWaste
teamEnergyExp = teamEnergyExp - cp.team_energyWaste
local extraMetalPull = spGetTeamRulesParam(myTeamID, "extraMetalPull") or 0
local extraEnergyPull = spGetTeamRulesParam(myTeamID, "extraEnergyPull") or 0
mPull = mPull + extraMetalPull
ePull = ePull + extraEnergyPull - math.min(0, cp.energyOverdrive)
mStor = mStor - HIDDEN_STORAGE -- reduce by hidden storage
eStor = eStor - HIDDEN_STORAGE -- reduce by hidden storage
if eCurr > eStor then
eCurr = eStor -- cap by storage
end
if options.onlyShowExpense.value then
eExpe = eExpe - cp.team_energyWaste/cp.allies -- if there is energy wastage, dont show it as used pull energy
else
ePull = ePull - cp.team_energyWaste/cp.allies
end
--// BLINK WHEN EXCESSING OR ON LOW ENERGY
local wastingM = mCurr >= mStor * 0.9
if wastingM then
blinkM_status = true
elseif (blinkM_status) then
blinkM_status = false
bar_metal:SetColor( col_metal )
end
local wastingE = false
if options.eexcessflashalways.value then
wastingE = (cp.team_energyWaste > 0)
else
local waste = ((cp.allies > 0 and cp.team_energyWaste/cp.allies) or 0)
wastingE = (waste > eInco*0.05) and (waste > 15)
end
local stallingE = (eCurr <= eStor * options.energyFlash.value) and (eCurr < 1000) and (eCurr >= 0)
if stallingE or wastingE then
blinkE_status = true
bar_energy:SetValue( 100 )
excessE = wastingE
elseif (blinkE_status) then
blinkE_status = false
bar_energy:SetColor( col_energy )
bar_energy_overlay:SetColor({0,0,0,0})
end
local mPercent = 100 * mCurr / mStor
local ePercent = 100 * eCurr / eStor
bar_metal:SetValue( mPercent )
if wastingM then
bar_metal_reserve_overlay:SetCaption( (GreenStr.."%i/%i"):format(mCurr, mStor) )
else
bar_metal_reserve_overlay:SetCaption( ("%i/%i"):format(mCurr, mStor) )
end
bar_energy:SetValue( ePercent )
if stallingE then
bar_energy_reserve_overlay:SetCaption( (RedStr.."%i/%i"):format(eCurr, eStor) )
elseif wastingE then
bar_energy_reserve_overlay:SetCaption( (GreenStr.."%i/%i"):format(eCurr, eStor) )
else
bar_energy_reserve_overlay:SetCaption( ("%i/%i"):format(eCurr, eStor) )
end
local metalBase = Format(cp.metalBase)
local metalOverdrive = Format(cp.metalOverdrive)
local metalReclaim = Format(math.max(0, mInco - cp.metalOverdrive - cp.metalBase - cp.metalMisc - mReci))
local metalConstructor = Format(cp.metalMisc)
local metalShare = Format(mReci - mSent)
local metalConstuction = Format(-mExpe)
local team_metalTotalIncome = Format(teamMInco)
local team_metalPull = Format(-teamMPull)
local team_metalBase = Format(cp.team_metalBase)
local team_metalOverdrive = Format(cp.team_metalOverdrive)
local team_metalReclaim = Format(math.max(0, teamMInco - cp.team_metalOverdrive - cp.team_metalBase - cp.team_metalMisc))
local team_metalConstructor = Format(cp.team_metalMisc)
local team_metalConstuction = Format(-teamMSpent)
local team_metalWaste = Format(math.min(teamFreeStorage + teamMSpent - teamMInco,0))
local energyGenerators = Format(cp.energyIncome)
local energyReclaim = Format(eReclaim)
local energyOverdrive = Format(cp.energyOverdrive)
local energyOther = Format(-eExpe + mExpe - math.min(0, cp.energyOverdrive))
local team_energyIncome = Format(teamEnergyIncome)
local team_energyGenerators = Format(cp.team_energyIncome)
local team_energyReclaim = Format(teamEnergyReclaim)
local team_energyPull = Format(-totalPull)
local team_energyOverdrive = Format(-cp.team_energyOverdrive)
local team_energyWaste = Format(-cp.team_energyWaste)
local team_energyOther = Format(-teamEnergyExp + teamMSpent + cp.team_energyOverdrive)
bar_metal.tooltip = "Local Metal Economy" ..
"\n Base Extraction: " .. metalBase ..
"\n Overdrive: " .. metalOverdrive ..
"\n Reclaim: " .. metalReclaim ..
"\n Cons: " .. metalConstructor ..
"\n Sharing: " .. metalShare ..
"\n Construction: " .. metalConstuction ..
"\n Reserve: " .. math.ceil(WG.metalStorageReserve or 0) ..
"\n Stored: " .. ("%i / %i"):format(mCurr, mStor) ..
"\n " ..
"\nTeam Metal Economy " ..
"\n Inc: " .. team_metalTotalIncome .. " Pull: " .. team_metalPull ..
"\n Base Extraction: " .. team_metalBase ..
"\n Overdrive: " .. team_metalOverdrive ..
"\n Reclaim : " .. team_metalReclaim ..
"\n Cons: " .. team_metalConstructor ..
"\n Construction: " .. team_metalConstuction ..
"\n Waste: " .. team_metalWaste ..
"\n Stored: " .. ("%i / %i"):format(teamTotalMetalStored, teamTotalMetalCapacity)
bar_energy.tooltip = "Local Energy Economy" ..
"\n Generators: " .. energyGenerators ..
"\n Reclaim: " .. energyReclaim ..
"\n Sharing & Overdrive: " .. energyOverdrive ..
"\n Construction: " .. metalConstuction ..
"\n Other: " .. energyOther ..
"\n Reserve: " .. math.ceil(WG.energyStorageReserve or 0) ..
"\n Stored: " .. ("%i / %i"):format(eCurr, eStor) ..
"\n " ..
"\nTeam Energy Economy" ..
"\n Inc: " .. team_energyIncome .. " Pull: " .. team_energyPull ..
"\n Generators: " .. team_energyGenerators ..
"\n Reclaim: " .. team_energyReclaim ..
"\n Overdrive: " .. team_energyOverdrive .. " -> " .. team_metalOverdrive .. " metal" ..
"\n Construction: " .. team_metalConstuction ..
"\n Other: " .. team_energyOther ..
"\n Waste: " .. team_energyWaste ..
"\n Stored: " .. ("%i / %i"):format(teamTotalEnergyStored, teamTotalEnergyCapacity)
local mTotal
if options.onlyShowExpense.value then
mTotal = mInco - mExpe + mReci
else
mTotal = mInco - mPull + mReci
end
if (mTotal >= 2) then
lbl_metal.font:SetColor(0,1,0,1)
elseif (mTotal > 0.1) then
lbl_metal.font:SetColor(1,0.7,0,1)
else
lbl_metal.font:SetColor(1,0,0,1)
end
local abs_mTotal = abs(mTotal)
if (abs_mTotal <0.1) then
lbl_metal:SetCaption( "\1770" )
elseif (abs_mTotal >=10)and((abs(mTotal%1)<0.1)or(abs_mTotal>99)) then
lbl_metal:SetCaption( ("%+.0f"):format(mTotal) )
else
lbl_metal:SetCaption( ("%+.1f"):format(mTotal) )
end
local eTotal
if options.onlyShowExpense.value then
eTotal = eInco - eExpe
else
eTotal = eInco - ePull
end
if (eTotal >= 2) then
lbl_energy.font:SetColor(0,1,0,1)
elseif (eTotal > 0.1) then
lbl_energy.font:SetColor(1,0.7,0,1)
--elseif ((eStore - eCurr) < 50) then --// prevents blinking when overdrive is active
-- lbl_energy.font:SetColor(0,1,0,1)
else
lbl_energy.font:SetColor(1,0,0,1)
end
local abs_eTotal = abs(eTotal)
if (abs_eTotal<0.1) then
lbl_energy:SetCaption( "\1770" )
elseif (abs_eTotal>=10)and((abs(eTotal%1)<0.1)or(abs_eTotal>99)) then
lbl_energy:SetCaption( ("%+.0f"):format(eTotal) )
else
lbl_energy:SetCaption( ("%+.1f"):format(eTotal) )
end
if options.onlyShowExpense.value then
lbl_m_expense:SetCaption( ("%.1f"):format(mExpe) )
lbl_e_expense:SetCaption( ("%.1f"):format(eExpe) )
else
lbl_m_expense:SetCaption( ("%.1f"):format(mPull) )
lbl_e_expense:SetCaption( ("%.1f"):format(ePull) )
end
lbl_m_income:SetCaption( ("%.1f"):format(mInco+mReci) )
lbl_e_income:SetCaption( ("%.1f"):format(eInco) )
if options.workerUsage.value then
local bp_aval = 0
local bp_use = 0
local builderIDs = Spring.GetTeamUnitsByDefs(GetMyTeamID(), builderDefs)
if (builderIDs) then
for i=1,#builderIDs do
local unit = builderIDs[i]
local ud = UnitDefs[Spring.GetUnitDefID(unit)]
local _, metalUse, _,energyUse = Spring.GetUnitResources(unit)
bp_use = bp_use + math.max(abs(metalUse), abs(energyUse))
bp_aval = bp_aval + ud.buildSpeed
end
end
if bp_aval == 0 then
bar_buildpower:SetValue(0)
bar_buildpower:SetCaption("no workers")
else
local buildpercent = bp_use/bp_aval * 100
bar_buildpower:SetValue(buildpercent)
bar_buildpower:SetCaption(("%.1f%%"):format(buildpercent))
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Shutdown()
window:Dispose()
end
function widget:Initialize()
Chili = WG.Chili
if (not Chili) then
widgetHandler:RemoveWidget()
return
end
--widgetHandler:RegisterGlobal("MexEnergyEvent", MexEnergyEvent)
--widgetHandler:RegisterGlobal("ReserveState", ReserveState)
--widgetHandler:RegisterGlobal("SendWindProduction", SendWindProduction)
--widgetHandler:RegisterGlobal("PriorityStats", PriorityStats)
time_old = GetTimer()
Spring.SendCommands("resbar 0")
CreateWindow()
end
function CreateWindow()
local bars = 2
if options.workerUsage.value then
bars = 3
end
local function p(a)
return tostring(a).."%"
end
-- Set the size for the default settings.
local screenWidth,screenHeight = Spring.GetWindowGeometry()
local width = 430
local x = math.min(screenWidth/2 - width/2, screenWidth - 400 - width)
--// WINDOW
window = Chili.Window:New{
color = {1,1,1,options.opacity.value},
parent = Chili.Screen0,
dockable = true,
name="ResourceBars",
padding = {0,0,0,0},
x = x,
y = 0,
width = 430,
height = 50,
draggable = false,
resizable = false,
tweakDraggable = true,
tweakResizable = true,
minimizable = false,
OnMouseDown={ function(self) --OnClick don't work here, probably because its children can steal click
local alt, ctrl, meta, shift = Spring.GetModKeyState()
if not meta then return false end
WG.crude.OpenPath(options_path)
WG.crude.ShowMenu()
return true
end },
}
--// METAL
Chili.Image:New{
parent = window,
height = p(100/bars),
width = 25,
y = p(100/bars),
right = 0,
file = 'LuaUI/Images/ibeam.png',
}
bar_metal_reserve_overlay = Chili.Progressbar:New{
parent = window,
color = {0.5,0.5,0.5,0.5},
height = p(100/bars),
right = 26,
min = 0,
max = 1,
value = 0,
x = 110,
y = p(100/bars),
noSkin = true,
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
}
bar_metal = Chili.Progressbar:New{
parent = window,
color = col_metal,
height = p(100/bars),
right = 26,
x = 110,
y = p(100/bars),
tooltip = "This shows your current metal reserves",
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
OnMouseDown = {function() return (not widgetHandler:InTweakMode()) end}, -- this is needed for OnMouseUp to work
OnMouseUp = {function(self, x, y, mouse)
if widgetHandler:InTweakMode() then return end
local reserve = x / (self.width - self.padding[1] - self.padding[3])
updateReserveBars(true, mouse ~= 3, reserve)
end},
}
lbl_metal = Chili.Label:New{
parent = window,
height = p(100/bars),
width = 60,
x = 10,
y = p(100/bars),
valign = "center",
align = "right",
caption = "0",
autosize = false,
font = {size = 19, outline = true, outlineWidth = 4, outlineWeight = 3,},
tooltip = "Your net metal income",
}
lbl_m_income = Chili.Label:New{
parent = window,
height = p(50/bars),
width = 40,
x = 70,
y = p(100/bars),
caption = "10.0",
valign = "center",
align = "center",
autosize = false,
font = {size = 12, outline = true, color = {0,1,0,1}},
tooltip = "Your metal Income.\nGained primarilly from metal extractors, overdrive and reclaim",
}
lbl_m_expense = Chili.Label:New{
parent = window,
height = p(50/bars),
width = 40,
x = 70,
y = p(1.5*100/bars),
caption = "10.0",
valign = "center",
align = "center",
autosize = false,
font = {size = 12, outline = true, color = {1,0,0,1}},
tooltip = "This is the metal demand of your construction",
}
--// ENERGY
Chili.Image:New{
parent = window,
height = p(100/bars),
width = 25,
right = 10,
y = 1,
file = 'LuaUI/Images/energy.png',
}
bar_energy_overlay = Chili.Progressbar:New{
parent = window,
color = col_energy,
height = p(100/bars),
value = 100,
color = {0,0,0,0},
right = 36,
x = 100,
y = 1,
noSkin = true,
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
}
bar_energy_reserve_overlay = Chili.Progressbar:New{
parent = window,
color = {0.5,0.5,0.5,0.5},
height = p(100/bars),
right = 26,
value = 0,
min = 0,
max = 1,
right = 36,
x = 100,
y = 1,
noSkin = true,
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
}
bar_energy = Chili.Progressbar:New{
parent = window,
color = col_energy,
height = p(100/bars),
right = 36,
x = 100,
y = 1,
tooltip = "Shows your current energy reserves.\n Anything above 100% will be burned by 'mex overdrive'\n which increases production of your mines",
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
OnMouseDown = {function() return (not widgetHandler:InTweakMode()) end}, -- this is needed for OnMouseUp to work
OnMouseUp = {function(self, x, y, mouse)
if widgetHandler:InTweakMode() then return end
local reserve = x / (self.width - self.padding[1] - self.padding[3])
updateReserveBars(mouse ~= 3, true, reserve)
end},
}
lbl_energy = Chili.Label:New{
parent = window,
height = p(100/bars),
width = 60,
x = 0,
y = 1,
valign = "center",
align = "right",
caption = "0",
autosize = false,
font = {size = 19, outline = true, outlineWidth = 4, outlineWeight = 3,},
tooltip = "Your net energy income.",
}
lbl_e_income = Chili.Label:New{
parent = window,
height = p(50/bars),
width = 40,
x = 60,
y = 1,
caption = "10.0",
valign = "center",
align = "center",
autosize = false,
font = {size = 12, outline = true, color = {0,1,0,1}},
tooltip = "Your energy income.\nGained from powerplants.",
}
lbl_e_expense = Chili.Label:New{
parent = window,
height = p(50/bars),
width = 40,
x = 60,
y = p(50/bars),
caption = "10.0",
valign = "center",
align = "center",
autosize = false,
font = {size = 12, outline = true, color = {1,0,0,1}},
tooltip = "This is the energy demand of your economy, cloakers, shields and overdrive",
}
-- Activate tooltips for lables and bars, they do not have them in default chili
function bar_metal:HitTest(x,y) return self end
function bar_energy:HitTest(x,y) return self end
function lbl_energy:HitTest(x,y) return self end
function lbl_metal:HitTest(x,y) return self end
function lbl_e_income:HitTest(x,y) return self end
function lbl_m_income:HitTest(x,y) return self end
function lbl_e_expense:HitTest(x,y) return self end
function lbl_m_expense:HitTest(x,y) return self end
if not options.workerUsage.value then return end
-- worker usage
bar_buildpower = Chili.Progressbar:New{
parent = window,
color = col_buildpower,
height = "33%",
right = 6,
x = 120,
y = "66%",
tooltip = "",
font = {color = {1,1,1,1}, outlineColor = {0,0,0,0.7}, },
}
end
function DestroyWindow()
window:Dispose()
window = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
RyMarq/Zero-K | LuaUI/Widgets/chili/Controls/progressbar.lua | 2 | 3879 | --// =============================================================================
--- Progressbar module
--- Progressbar fields.
-- Inherits from Control.
-- @see control.Control
-- @table Progressbar
-- @int[opt = 0] min minimum value of the Progressbar
-- @int[opt = 100] max maximum value of the Progressbar
-- @int[opt = 100] value value of the Progressbar
-- @string[opt = ""] caption text to be displayed
-- @tparam {r, g, b, a} color specifies the color of the bar (default: {0, 0, 1, 1})
-- @tparam {r, g, b, a} backgroundColor specifies the background color (default: {1, 1, 1, 1})
-- @tparam {func1, fun2, ...} OnChange function listeners for value change (default {})
Progressbar = Control:Inherit{
classname = "progressbar",
defaultWidth = 90,
defaultHeight = 20,
min = 0,
max = 100,
value = 100,
orientation = "horizontal",
reverse = false,
caption = "",
noFont = false,
color = {0, 0, 1, 1},
backgroundColor = {1, 1, 1, 1},
OnChange = {},
}
local this = Progressbar
local inherited = this.inherited
--// =============================================================================
function Progressbar:New(obj)
obj = inherited.New(self, obj)
obj:SetMinMax(obj.min, obj.max)
obj:SetValue(obj.value)
return obj
end
--// =============================================================================
function Progressbar:_Clamp(v)
if (self.min < self.max) then
if (v < self.min) then
v = self.min
elseif (v > self.max) then
v = self.max
end
else
if (v > self.min) then
v = self.min
elseif (v < self.max) then
v = self.max
end
end
return v
end
--// =============================================================================
--- Sets the new color
-- @tparam {r, g, b, a} c color table
function Progressbar:SetColor(...)
local color = _ParseColorArgs(...)
table.merge(color, self.color)
if (not table.iequal(color, self.color)) then
self.color = color
self:Invalidate()
end
end
--- Sets the minimum and maximum value of the progress bar
-- @int[opt = 0] min minimum value
-- @int[opt = 1] max maximum value (why is 1 the default?)
function Progressbar:SetMinMax(min, max)
self.min = tonumber(min) or 0
self.max = tonumber(max) or 1
self:SetValue(self.value)
end
--- Sets the value of the progress bar
-- @int v value of the progress abr
-- @bool[opt = false] setcaption whether the caption should be set as well
function Progressbar:SetValue(v, setcaption)
v = self:_Clamp(v)
local oldvalue = self.value
if (v ~= oldvalue) then
self.value = v
if (setcaption) then
self:SetCaption(v)
end
self:CallListeners(self.OnChange, v, oldvalue)
self:Invalidate()
end
end
--- Sets the caption
-- @string str caption to be set
function Progressbar:SetCaption(str)
if (self.caption ~= str) then
self.caption = str
self:Invalidate()
end
end
--// =============================================================================
function Progressbar:DrawControl()
local percent = (self.value-self.min)/(self.max-self.min)
local w = self.width
local h = self.height
gl.Color(self.backgroundColor)
if (self.orientation == "horizontal") then
if self.reverse then
gl.Rect(0, 0, w*(1-percent), h)
else
gl.Rect(w*percent, 0, w, h)
end
else
if self.reverse then
gl.Rect(0, 0, w, h*percent)
else
gl.Rect(0, h*(1-percent), w, h)
end
end
gl.Color(self.color)
if (self.orientation == "horizontal") then
if self.reverse then
gl.Rect(w*(1-percent), 0, w, h)
else
gl.Rect(0, 0, w*percent, h)
end
else
if self.reverse then
gl.Rect(0, h*percent, w, h)
else
gl.Rect(0, 0, w, h*(1-percent))
end
end
if (self.caption) and not self.noFont then
(self.font):Print(self.caption, w*0.5, h*0.5, "center", "center")
end
end
--// =============================================================================
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/FeiYin/npcs/qm1.lua | 1 | 1512 | -----------------------------------
-- Area: FeiYin
-- NPC: ???
-- Involved In Quest: Pieuje's Decision
-- @zone 204
-- @pos -55 -16 69
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,PIEUJE_S_DECISION) == QUEST_ACCEPTED and player:hasItem(13842) == false) then
if(trade:hasItemQty(1098,1) and trade:getItemCount() == 1) then -- Trade Tavnazia Bell
player:tradeComplete();
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17612836,180):updateEnmity(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(THERE_IS_NOTHING_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);
end; | gpl-3.0 |
ferronrsmith/google-diff-match-patch | lua/diff_match_patch_test.lua | 264 | 39109 | --[[
* Test Harness for Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser
* Ported to Lua by Duncan Cross
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
local dmp = require 'diff_match_patch'
local DIFF_INSERT = dmp.DIFF_INSERT
local DIFF_DELETE = dmp.DIFF_DELETE
local DIFF_EQUAL = dmp.DIFF_EQUAL
-- Utility functions.
local function pretty(v)
if (type(v) == 'string') then
return string.format('%q', v):gsub('\\\n', '\\n')
elseif (type(v) == 'table') then
local str = {}
local next_i = 1
for i, v in pairs(v) do
if (i == next_i) then
next_i = next_i + 1
str[#str + 1] = pretty(v)
else
str[#str + 1] = '[' .. pretty(i) .. ']=' .. pretty(v)
end
end
return '{' .. table.concat(str, ',') .. '}'
else
return tostring(v)
end
end
function assertEquals(...)
local msg, expected, actual
if (select('#', ...) == 2) then
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
else
msg, expected, actual = ...
end
assert(expected == actual, msg)
end
function assertTrue(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(true, actual)
else
msg, actual = ...
assertEquals(msg, true, actual)
end
end
function assertFalse(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(flase, actual)
else
msg, actual = ...
assertEquals(msg, false, actual)
end
end
-- If expected and actual are the equivalent, pass the test.
function assertEquivalent(...)
local msg, expected, actual
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
if (_equivalent(expected, actual)) then
assertEquals(msg, pretty(expected), pretty(actual))
else
assertEquals(msg, expected, actual)
end
end
-- Are a and b the equivalent? -- Recursive.
function _equivalent(a, b)
if (a == b) then
return true
end
if (type(a) == 'table') and (type(b) == 'table') then
for k, v in pairs(a) do
if not _equivalent(v, b[k]) then
return false
end
end
for k, v in pairs(b) do
if not _equivalent(v, a[k]) then
return false
end
end
return true
end
return false
end
function diff_rebuildtexts(diffs)
-- Construct the two texts which made up the diff originally.
local text1, text2 = {}, {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op ~= DIFF_INSERT) then
text1[#text1 + 1] = data
end
if (op ~= DIFF_DELETE) then
text2[#text2 + 1] = data
end
end
return table.concat(text1), table.concat(text2)
end
-- DIFF TEST FUNCTIONS
function testDiffCommonPrefix()
-- Detect any common prefix.
-- Null case.
assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz'))
-- Whole case.
assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz'))
end
function testDiffCommonSuffix()
-- Detect any common suffix.
-- Null case.
assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234'))
-- Whole case.
assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234'))
end
function testDiffCommonOverlap()
-- Detect any suffix/prefix overlap.
-- Null case.
assertEquals(0, dmp.diff_commonOverlap('', 'abcd'));
-- Whole case.
assertEquals(3, dmp.diff_commonOverlap('abc', 'abcd'));
-- No overlap.
assertEquals(0, dmp.diff_commonOverlap('123456', 'abcd'));
-- Overlap.
assertEquals(3, dmp.diff_commonOverlap('123456xxx', 'xxxabcd'));
--[[
-- Unicode.
-- Some overly clever languages (C#) may treat ligatures as equal to their
-- component letters. E.g. U+FB01 == 'fi'
-- LUANOTE: No ability to handle Unicode.
assertEquals(0, dmp.diff_commonOverlap('fi', '\ufb01i'));
--]]
end
function testDiffHalfMatch()
-- Detect a halfmatch.
dmp.settings{Diff_Timeout = 1}
-- No match.
assertEquivalent({nil}, {dmp.diff_halfMatch('1234567890', 'abcdef')})
assertEquivalent({nil}, {dmp.diff_halfMatch('12345', '23')})
-- Single Match.
assertEquivalent({'12', '90', 'a', 'z', '345678'},
{dmp.diff_halfMatch('1234567890', 'a345678z')})
assertEquivalent({'a', 'z', '12', '90', '345678'},
{dmp.diff_halfMatch('a345678z', '1234567890')})
assertEquivalent({'abc', 'z', '1234', '0', '56789'},
{dmp.diff_halfMatch('abc56789z', '1234567890')})
assertEquivalent({'a', 'xyz', '1', '7890', '23456'},
{dmp.diff_halfMatch('a23456xyz', '1234567890')})
-- Multiple Matches.
assertEquivalent({'12123', '123121', 'a', 'z', '1234123451234'},
{dmp.diff_halfMatch('121231234123451234123121', 'a1234123451234z')})
assertEquivalent({'', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='},
{dmp.diff_halfMatch('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')})
assertEquivalent({'-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'},
{dmp.diff_halfMatch('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')})
-- Non-optimal halfmatch.
-- Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy
assertEquivalent({'qHillo', 'w', 'x', 'Hulloy', 'HelloHe'},
{dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
-- Optimal no halfmatch.
dmp.settings{Diff_Timeout = 0}
assertEquivalent({nill}, {dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
end
function testDiffCleanupMerge()
-- Cleanup a messy diff.
-- Null case.
local diffs = {}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({}, diffs)
-- No change case.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}},
diffs)
-- Merge equalities.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'abc'}}, diffs)
-- Merge deletions.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}}, diffs)
-- Merge insertions.
diffs = {{DIFF_INSERT, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'abc'}}, diffs)
-- Merge interweave.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_DELETE, 'c'},
{DIFF_INSERT, 'd'}, {DIFF_EQUAL, 'e'}, {DIFF_EQUAL, 'f'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'ac'}, {DIFF_INSERT, 'bd'}, {DIFF_EQUAL, 'ef'}},
diffs)
-- Prefix and suffix detection.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'}, {DIFF_DELETE, 'dc'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'c'}}, diffs)
-- Prefix and suffix detection with equalities.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'},
{DIFF_DELETE, 'dc'}, {DIFF_EQUAL, 'y'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'cy'}}, diffs)
-- Slide edit left.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_INSERT, 'ba'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'ac'}}, diffs)
-- Slide edit right.
diffs = {{DIFF_EQUAL, 'c'}, {DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'ca'}, {DIFF_INSERT, 'ba'}}, diffs)
-- Slide edit left recursive.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'ac'}, {DIFF_EQUAL, 'x'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'acx'}}, diffs)
-- Slide edit right recursive.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'ca'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xca'}, {DIFF_DELETE, 'cba'}}, diffs)
end
function testDiffCleanupSemanticLossless()
-- Slide diffs to match logical boundaries.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({}, diffs)
-- Blank lines.
diffs = {{DIFF_EQUAL, 'AAA\r\n\r\nBBB'}, {DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'},
{DIFF_EQUAL, '\r\nEEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n\r\n'},
{DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'}, {DIFF_EQUAL, 'BBB\r\nEEE'}}, diffs)
-- Line boundaries.
diffs = {{DIFF_EQUAL, 'AAA\r\nBBB'}, {DIFF_INSERT, ' DDD\r\nBBB'},
{DIFF_EQUAL, ' EEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n'}, {DIFF_INSERT, 'BBB DDD\r\n'},
{DIFF_EQUAL, 'BBB EEE'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_INSERT, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_INSERT, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Alphanumeric boundaries.
diffs = {{DIFF_EQUAL, 'The-c'}, {DIFF_INSERT, 'ow-and-the-c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The-'}, {DIFF_INSERT, 'cow-and-the-'},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Hitting the start.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'ax'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'aax'}}, diffs)
-- Hitting the end.
diffs = {{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'xaa'}, {DIFF_DELETE, 'a'}}, diffs)
-- Sentence boundaries.
diffs = {{DIFF_EQUAL, 'The xxx. The '}, {DIFF_INSERT, 'zzz. The '},
{DIFF_EQUAL, 'yyy.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The xxx.'}, {DIFF_INSERT, ' The zzz.'},
{DIFF_EQUAL, ' The yyy.'}}, diffs)
end
function testDiffCleanupSemantic()
-- Cleanup semantically trivial equalities.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({}, diffs)
-- No elimination #1.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}, diffs)
-- No elimination #2.
diffs = {{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}, diffs)
-- Simple elimination.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'b'}}, diffs)
-- Backpass elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_EQUAL, 'cd'}, {DIFF_DELETE, 'e'},
{DIFF_EQUAL, 'f'}, {DIFF_INSERT, 'g'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcdef'}, {DIFF_INSERT, 'cdfg'}}, diffs)
-- Multiple eliminations.
diffs = {{DIFF_INSERT, '1'}, {DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'},
{DIFF_INSERT, '2'}, {DIFF_EQUAL, '_'}, {DIFF_INSERT, '1'},
{DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'}, {DIFF_INSERT, '2'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'AB_AB'}, {DIFF_INSERT, '1A2_1A2'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_DELETE, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_DELETE, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- No overlap elimination.
diffs = {{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}, diffs)
-- Overlap elimination.
diffs = {{DIFF_DELETE, 'abcxxx'}, {DIFF_INSERT, 'xxxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'xxx'}, {DIFF_INSERT, 'def'}}, diffs)
-- Reverse overlap elimination.
diffs = {{DIFF_DELETE, 'xxxabc'}, {DIFF_INSERT, 'defxxx'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_INSERT, 'def'}, {DIFF_EQUAL, 'xxx'}, {DIFF_DELETE, 'abc'}}, diffs)
-- Two overlap eliminations.
diffs = {{DIFF_DELETE, 'abcd1212'}, {DIFF_INSERT, '1212efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A3'}, {DIFF_INSERT, '3BC'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcd'}, {DIFF_EQUAL, '1212'}, {DIFF_INSERT, 'efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A'}, {DIFF_EQUAL, '3'}, {DIFF_INSERT, 'BC'}}, diffs)
end
function testDiffCleanupEfficiency()
-- Cleanup operationally trivial equalities.
local diffs
dmp.settings{Diff_EditCost = 4}
-- Null case.
diffs = {}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({}, diffs)
-- No elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}, diffs)
-- Four-edit elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xyz34'}
}, diffs)
-- Three-edit elimination.
diffs = {
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'xcd'},
{DIFF_INSERT, '12x34'}
}, diffs)
-- Backpass elimination.
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'xy'},
{DIFF_INSERT, '34'},
{DIFF_EQUAL, 'z'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '56'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xy34z56'}
}, diffs)
-- High cost elimination.
dmp.settings{Diff_EditCost = 5}
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abwxyzcd'},
{DIFF_INSERT, '12wxyz34'}
}, diffs)
dmp.settings{Diff_EditCost = 4}
end
function testDiffPrettyHtml()
-- Pretty print.
local diffs = {
{DIFF_EQUAL, 'a\n'},
{DIFF_DELETE, '<B>b</B>'},
{DIFF_INSERT, 'c&d'}
}
assertEquals(
'<span>a¶<br></span>'
.. '<del style="background:#ffe6e6;"><B>b</B>'
.. '</del><ins style="background:#e6ffe6;">c&d</ins>',
dmp.diff_prettyHtml(diffs)
)
end
function testDiffText()
-- Compute the source and destination texts.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'}
}
assertEquals('jumps over the lazy', dmp.diff_text1(diffs))
assertEquals('jumped over a lazy', dmp.diff_text2(diffs))
end
function testDiffDelta()
-- Convert a diff into delta string.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'},
{DIFF_INSERT, 'old dog'}
}
local text1 = dmp.diff_text1(diffs)
assertEquals('jumps over the lazy', text1)
local delta = dmp.diff_toDelta(diffs)
assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Generates error (19 ~= 20).
success, result = pcall(dmp.diff_fromDelta, text1 .. 'x', delta)
assertEquals(false, success)
-- Generates error (19 ~= 18).
success, result = pcall(dmp.diff_fromDelta, string.sub(text1, 2), delta)
assertEquals(false, success)
-- Generates error (%c3%xy invalid Unicode).
success, result = pcall(dmp.patch_fromDelta, '', '+%c3%xy')
assertEquals(false, success)
--[[
-- Test deltas with special characters.
-- LUANOTE: No ability to handle Unicode.
diffs = {{DIFF_EQUAL, '\u0680 \000 \t %'}, {DIFF_DELETE, '\u0681 \x01 \n ^'}, {DIFF_INSERT, '\u0682 \x02 \\ |'}}
text1 = dmp.diff_text1(diffs)
assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1)
delta = dmp.diff_toDelta(diffs)
assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta)
--]]
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Verify pool of unchanged characters.
diffs = {
{DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # '}
}
local text2 = dmp.diff_text2(diffs)
assertEquals(
'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
text2
)
delta = dmp.diff_toDelta(diffs)
assertEquals(
'+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
delta
)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta('', delta))
end
function testDiffXIndex()
-- Translate a location in text1 to text2.
-- Translation on equality.
assertEquals(6, dmp.diff_xIndex({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 3))
-- Translation on deletion.
assertEquals(2, dmp.diff_xIndex({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 4))
end
function testDiffLevenshtein()
-- Levenshtein with trailing equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}))
-- Levenshtein with leading equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'}
}))
-- Levenshtein with middle equality.
assertEquals(7, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_EQUAL, 'xyz'},
{DIFF_INSERT, '1234'}
}))
end
function testDiffBisect()
-- Normal.
local a = 'cat'
local b = 'map'
-- Since the resulting diff hasn't been normalized, it would be ok if
-- the insertion and deletion pairs are swapped.
-- If the order changes, tweak this test as required.
assertEquivalent({
{DIFF_DELETE, 'c'},
{DIFF_INSERT, 'm'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 't'},
{DIFF_INSERT, 'p'}
}, dmp.diff_bisect(a, b, 2 ^ 31))
-- Timeout.
assertEquivalent({
{DIFF_DELETE, 'cat'},
{DIFF_INSERT, 'map'}
}, dmp.diff_bisect(a, b, 0))
end
function testDiffMain()
-- Perform a trivial diff.
local a,b
-- Null case.
assertEquivalent({}, dmp.diff_main('', '', false))
-- Equality.
assertEquivalent({
{DIFF_EQUAL, 'abc'}
}, dmp.diff_main('abc', 'abc', false))
-- Simple insertion.
assertEquivalent({
{DIFF_EQUAL, 'ab'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'ab123c', false))
-- Simple deletion.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'bc'}
}, dmp.diff_main('a123bc', 'abc', false))
-- Two insertions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_INSERT, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'a123b456c', false))
-- Two deletions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('a123b456c', 'abc', false))
-- Perform a real diff.
-- Switch off the timeout.
dmp.settings{ Diff_Timeout=0 }
-- Simple cases.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, 'b'}
}, dmp.diff_main('a', 'b', false))
assertEquivalent({
{DIFF_DELETE, 'Apple'},
{DIFF_INSERT, 'Banana'},
{DIFF_EQUAL, 's are a'},
{DIFF_INSERT, 'lso'},
{DIFF_EQUAL, ' fruit.'}
}, dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false))
--[[
-- LUANOTE: No ability to handle Unicode.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '\u0680'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, '\t'},
{DIFF_INSERT, '\0'}
}, dmp.diff_main('ax\t', '\u0680x\0', false))
]]--
-- Overlaps.
assertEquivalent({
{DIFF_DELETE, '1'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 'y'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '2'},
{DIFF_INSERT, 'xab'}
}, dmp.diff_main('1ayb2', 'abxab', false))
assertEquivalent({
{DIFF_INSERT, 'xaxcx'},
{DIFF_EQUAL, 'abc'},
{DIFF_DELETE, 'y'}
}, dmp.diff_main('abcy', 'xaxcxabc', false))
assertEquivalent({
{DIFF_DELETE, 'ABCD'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'bcd'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'efghijklmnopqrs'},
{DIFF_DELETE, 'EFGHIJKLMNOefg'}
}, dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg',
'a-bcd-efghijklmnopqrs', false))
-- Large equality.
assertEquivalent({
{DIFF_INSERT, ' '},
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, 'nd'},
{DIFF_EQUAL, ' [[Pennsylvania]]'},
{DIFF_DELETE, ' and [[New'}
}, dmp.diff_main('a [[Pennsylvania]] and [[New',
' and [[Pennsylvania]]', false))
-- Timeout.
dmp.settings{Diff_Timeout = 0.1} -- 100ms
-- Increase the text lengths by 1024 times to ensure a timeout.
a = string.rep([[
`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
]], 1024)
b = string.rep([[
I am the very model of a modern major general,
I've information vegetable, animal, and mineral,
I know the kings of England, and I quote the fights historical,
From Marathon to Waterloo, in order categorical.
]], 1024)
local startTime = os.clock()
dmp.diff_main(a, b)
local endTime = os.clock()
-- Test that we took at least the timeout period.
assertTrue(0.1 <= endTime - startTime)
-- Test that we didn't take forever (be forgiving).
-- Theoretically this test could fail very occasionally if the
-- OS task swaps or locks up for a second at the wrong moment.
assertTrue(0.1 * 2 > endTime - startTime)
dmp.settings{Diff_Timeout = 0}
-- Test the linemode speedup.
-- Must be long to pass the 100 char cutoff.
-- Simple line-mode.
a = string.rep('1234567890\n', 13)
b = string.rep('abcdefghij\n', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Single line-mode.
a = string.rep('1234567890', 13)
b = string.rep('abcdefghij', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Overlap line-mode.
a = string.rep('1234567890\n', 13)
b = [[
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
]]
local texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true))
local texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false))
assertEquivalent(texts_textmode, texts_linemode)
-- Test null inputs.
success, result = pcall(dmp.diff_main, nil, nil)
assertEquals(false, success)
end
-- MATCH TEST FUNCTIONS
function testMatchAlphabet()
-- Initialise the bitmasks for Bitap.
-- Unique.
assertEquivalent({a=4, b=2, c=1}, dmp.match_alphabet('abc'))
-- Duplicates.
assertEquivalent({a=37, b=18, c=8}, dmp.match_alphabet('abcaba'))
end
function testMatchBitap()
-- Bitap algorithm.
dmp.settings{Match_Distance=100, Match_Threshold=0.5}
-- Exact matches.
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 6))
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 1))
-- Fuzzy matches.
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxhi', 1))
assertEquals(3, dmp.match_bitap('abcdefghijk', 'cdefxyhijk', 6))
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'bxy', 2))
-- Overflow.
assertEquals(3, dmp.match_bitap('123456789xx0', '3456789x0', 3))
-- Threshold test.
dmp.settings{Match_Threshold = 0.4}
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.3}
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.0}
assertEquals(2, dmp.match_bitap('abcdefghijk', 'bcdef', 2))
dmp.settings{Match_Threshold = 0.5}
-- Multiple select.
assertEquals(1, dmp.match_bitap('abcdexyzabcde', 'abccde', 4))
assertEquals(9, dmp.match_bitap('abcdexyzabcde', 'abccde', 6))
-- Distance test.
dmp.settings{Match_Distance = 10} -- Strict location.
assertEquals(-1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 2))
dmp.settings{Match_Distance = 1000} -- Loose location.
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
end
function testMatchMain()
-- Full match.
-- Shortcut matches.
assertEquals(1, dmp.match_main('abcdef', 'abcdef', 1000))
assertEquals(-1, dmp.match_main('', 'abcdef', 2))
assertEquals(4, dmp.match_main('abcdef', '', 4))
assertEquals(4, dmp.match_main('abcdef', 'de', 4))
-- Beyond end match.
assertEquals(4, dmp.match_main("abcdef", "defy", 5))
-- Oversized pattern.
assertEquals(1, dmp.match_main("abcdef", "abcdefy", 1))
-- Complex match.
assertEquals(5, dmp.match_main(
'I am the very model of a modern major general.',
' that berry ',
6
))
-- Test null inputs.
success, result = pcall(dmp.match_main, nil, nil, 0)
assertEquals(false, success)
end
-- PATCH TEST FUNCTIONS
function testPatchObj()
-- Patch Object.
local p = dmp.new_patch_obj()
p.start1 = 21
p.start2 = 22
p.length1 = 18
p.length2 = 17
p.diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, '\nlaz'}
}
local strp = tostring(p)
assertEquals(
'@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n',
strp
)
end
function testPatchFromText()
local strp
strp = ''
assertEquivalent({}, dmp.patch_fromText(strp))
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n'
assertEquals(strp, tostring(dmp.patch_fromText(strp)[1]))
assertEquals(
'@@ -1 +1 @@\n-a\n+b\n',
tostring(dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[1])
)
assertEquals(
'@@ -1,3 +0,0 @@\n-abc\n',
tostring(dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[1])
)
assertEquals(
'@@ -0,0 +1,3 @@\n+abc\n',
tostring(dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[1])
)
-- Generates error.
success, result = pcall(dmp.patch_fromText, 'Bad\nPatch\n')
assertEquals(false, success)
end
function testPatchToText()
local strp, p
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n'
.. '@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
end
function testPatchAddContext()
local p
dmp.settings{Patch_Margin = 4}
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps over the lazy dog.')
assertEquals(
'@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n',
tostring(p)
)
-- Same, but not enough trailing context.
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals(
'@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n',
tostring(p)
)
-- Same, but not enough leading context.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', tostring(p))
-- Same, but with ambiguity.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps. The quick brown fox crashes.')
assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', tostring(p))
end
function testPatchMake()
-- Null case.
local patches = dmp.patch_make('', '')
assertEquals('', dmp.patch_toText(patches))
local text1 = 'The quick brown fox jumps over the lazy dog.'
local text2 = 'That quick brown fox jumped over a lazy dog.'
-- Text2+Text1 inputs.
local expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n'
.. '@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n'
-- The second patch must be "-21,17 +21,18",
-- not "-22,17 +21,18" due to rolling context.
patches = dmp.patch_make(text2, text1)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2 inputs.
expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n'
.. '@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Diff input.
local diffs = dmp.diff_main(text1, text2, false)
patches = dmp.patch_make(diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Diff inputs.
patches = dmp.patch_make(text1, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2+Diff inputs (deprecated).
patches = dmp.patch_make(text1, text2, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Character encoding.
patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|="<>?')
assertEquals('@@ -1,21 +1,21 @@\n'
.. '-%601234567890-=%5B%5D%5C;\',./\n'
.. '+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n', dmp.patch_toText(patches))
-- Character decoding.
diffs = {
{DIFF_DELETE, '`1234567890-=[]\\;\',./'},
{DIFF_INSERT, '~!@#$%^&*()_+{}|="<>?'}
}
assertEquivalent(diffs, dmp.patch_fromText(
'@@ -1,21 +1,21 @@'
.. '\n-%601234567890-=%5B%5D%5C;\',./'
.. '\n+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n'
)[1].diffs)
-- Long string with repeats.
text1 = string.rep('abcdef', 100)
text2 = text1 .. '123'
expectedPatch = '@@ -573,28 +573,31 @@\n'
.. ' cdefabcdefabcdefabcdefabcdef\n+123\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Test null inputs.
success, result = pcall(dmp.patch_make, nil, nil)
assertEquals(false, success)
end
function testPatchSplitMax()
-- Assumes that dmp.Match_MaxBits is 32.
local patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890',
'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz')
local oldToText = dmp.patch_toText(patches)
dmp.patch_splitMax(patches)
assertEquals(oldToText, dmp.patch_toText(patches))
patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1', 'abcdefghij , h = 1 , t = 1 abcdefghij , h = 1 , t = 1 abcdefghij , h = 0 , t = 1')
dmp.patch_splitMax(patches)
assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n', dmp.patch_toText(patches))
end
function testPatchAddPadding()
-- Both edges full.
local patches = dmp.patch_make('', 'test')
assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches))
-- Both edges partial.
patches = dmp.patch_make('XY', 'XtestY')
assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches))
-- Both edges none.
patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY')
assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
end
function testPatchApply()
local patches
dmp.settings{Match_Distance = 1000}
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Null case.
patches = dmp.patch_make('', '')
assertEquivalent({'Hello world.', {}},
{dmp.patch_apply(patches, 'Hello world.')})
-- Exact match.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'That quick brown fox jumped over a lazy dog.')
assertEquivalent(
{'That quick brown fox jumped over a lazy dog.', {true, true}},
{dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')})
-- Partial match.
assertEquivalent(
{'That quick red rabbit jumped over a tired tiger.', {true, true}},
{dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.')})
-- Failed match.
assertEquivalent(
{'I am the very model of a modern major general.', {false, false}},
{dmp.patch_apply(patches, 'I am the very model of a modern major general.')})
-- Big delete, small change.
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789012345678901234567890y',
'xabcy')
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(patches,
'x123456789012345678901234567890-----++++++++++-----'
.. '123456789012345678901234567890y')})
-- Big delete, big change 1.
patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y', 'xabcy')
assertEquivalent({'xabc12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y', {false, true}},
{dmp.patch_apply(patches, 'x12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y'
)})
-- Big delete, big change 2.
dmp.settings{Patch_DeleteThreshold = 0.6}
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y',
'xabcy'
)
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(
patches,
'x12345678901234567890---------------++++++++++---------------'
.. '12345678901234567890y'
)}
)
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Compensate for failed patch.
dmp.settings{Match_Threshold = 0, Match_Distance = 0}
patches = dmp.patch_make(
'abcdefghijklmnopqrstuvwxyz--------------------1234567890',
'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------'
.. '1234567YYYYYYYYYY890'
)
assertEquivalent({
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890',
{false, true}
}, {dmp.patch_apply(
patches,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890'
)})
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Match_Distance = 1000}
-- No side effects.
patches = dmp.patch_make('', 'test')
local patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, '')
assertEquals(patchstr, dmp.patch_toText(patches))
-- No side effects with major delete.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'Woof')
patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')
assertEquals(patchstr, dmp.patch_toText(patches))
-- Edge exact match.
patches = dmp.patch_make('', 'test')
assertEquivalent({'test', {true}}, {dmp.patch_apply(patches, '')})
-- Near edge exact match.
patches = dmp.patch_make('XY', 'XtestY')
assertEquivalent({'XtestY', {true}}, {dmp.patch_apply(patches, 'XY')})
-- Edge partial match.
patches = dmp.patch_make('y', 'y123')
assertEquivalent({'x123', {true}}, {dmp.patch_apply(patches, 'x')})
end
function runTests()
local passed = 0
local failed = 0
for name, func in pairs(_G) do
if (type(func) == 'function') and tostring(name):match("^test") then
local success, message = pcall(func)
if success then
print(name .. ' Ok.')
passed = passed + 1
else
print('** ' .. name .. ' FAILED: ' .. tostring(message))
failed = failed + 1
end
end
end
print('Tests passed: ' .. passed)
print('Tests failed: ' .. failed)
if failed ~= 0 then
os.exit(1)
end
end
runTests()
| apache-2.0 |
TerminalShell/zombiesurvival | entities/entities/prop_gunturret/shared.lua | 1 | 6411 | ENT.Type = "anim"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.SearchDistance = 768
ENT.MinimumAimDot = 0.5
ENT.DefaultAmmo = 250
ENT.MaxAmmo = 250
ENT.PosePitch = 0
ENT.PoseYaw = 0
ENT.m_NoNailUnfreeze = true
ENT.NoNails = true
ENT.CanPackUp = true
ENT.IsBarricadeObject = true
ENT.AlwaysGhostable = true
function ENT:GetLocalAnglesToTarget(target)
return self:WorldToLocalAngles(self:GetAnglesToTarget(target))
end
function ENT:GetAnglesToTarget(target)
return self:GetAnglesToPos(self:GetTargetPos(target))
end
function ENT:GetLocalAnglesToPos(pos)
return self:WorldToLocalAngles(self:GetAnglesToPos(pos))
end
function ENT:GetAnglesToPos(pos)
return (pos - self:ShootPos()):Angle()
end
function ENT:IsValidTarget(target)
return target:IsPlayer() and target:Team() == TEAM_UNDEAD and target:Alive() and self:GetForward():Dot(self:GetAnglesToTarget(target):Forward()) >= self.MinimumAimDot and TrueVisible(self:ShootPos(), self:GetTargetPos(target), self)
end
function ENT:GetManualTrace()
local owner = self:GetObjectOwner()
local filter = owner:GetMeleeFilter()
table.insert(filter, self)
return owner:TraceLine(4096, MASK_SOLID, filter)
end
function ENT:CalculatePoseAngles()
local owner = self:GetObjectOwner()
if not owner:IsValid() or self:GetAmmo() <= 0 or self:GetMaterial() ~= "" then
self.PoseYaw = math.Approach(self.PoseYaw, 0, FrameTime() * 60)
self.PosePitch = math.Approach(self.PosePitch, 15, FrameTime() * 30)
return
end
if self:GetManualControl() then
local ang = self:GetLocalAnglesToPos(self:GetManualTrace().HitPos)
self.PoseYaw = math.Approach(self.PoseYaw, math.Clamp(math.NormalizeAngle(ang.yaw), -60, 60), FrameTime() * 140)
self.PosePitch = math.Approach(self.PosePitch, math.Clamp(math.NormalizeAngle(ang.pitch), -15, 15), FrameTime() * 140)
else
local target = self:GetTarget()
if target:IsValid() then
local ang = self:GetLocalAnglesToTarget(target)
self.PoseYaw = math.Approach(self.PoseYaw, math.Clamp(math.NormalizeAngle(ang.yaw), -60, 60), FrameTime() * 140)
self.PosePitch = math.Approach(self.PosePitch, math.Clamp(math.NormalizeAngle(ang.pitch), -15, 15), FrameTime() * 100)
else
local ct = CurTime()
self.PoseYaw = math.Approach(self.PoseYaw, math.sin(ct) * 45, FrameTime() * 60)
self.PosePitch = math.Approach(self.PosePitch, math.cos(ct * 1.4) * 15, FrameTime() * 30)
end
end
end
function ENT:GetScanFilter()
local filter = team.GetPlayers(TEAM_HUMAN)
filter[#filter + 1] = self
return filter
end
-- Getting all of some team is straining every frame when there's 5 or so turrets. I could probably use CONTENTS_TEAM* if I knew what they did.
ENT.NextCache = 0
function ENT:GetCachedScanFilter()
if CurTime() < self.NextCache and self.CachedFilter then return self.CachedFilter end
self.CachedFilter = self:GetScanFilter()
self.NextCache = CurTime() + 1
return self.CachedFilter
end
local tabSearch = {mask = MASK_SHOT}
function ENT:SearchForTarget()
local shootpos = self:ShootPos()
tabSearch.start = shootpos
tabSearch.endpos = shootpos + self:GetGunAngles():Forward() * self.SearchDistance
tabSearch.filter = self:GetCachedScanFilter()
local tr = util.TraceLine(tabSearch)
local ent = tr.Entity
if ent and ent:IsValid() and self:IsValidTarget(ent) then
return ent
end
end
function ENT:GetTargetPos(target)
local boneid = target:GetHitBoxBone(HITGROUP_HEAD, 0)
if boneid and boneid > 0 then
local p, a = target:GetBonePosition(boneid)
if p then
return p
end
end
return target:LocalToWorld(target:OBBCenter())
end
function ENT:HumanHoldable(pl)
return true
end
function ENT:DefaultPos()
return self:GetPos() + self:GetUp() * 55
end
function ENT:ShootPos()
local attachid = self:LookupAttachment("eyes")
if attachid then
local attach = self:GetAttachment(attachid)
if attach then return attach.Pos end
end
return self:DefaultPos()
end
function ENT:LaserPos()
local attachid = self:LookupAttachment("light")
if attachid then
local attach = self:GetAttachment(attachid)
if attach then return attach.Pos end
end
return self:DefaultPos()
end
ENT.LightPos = ENT.LaserPos
function ENT:GetGunAngles()
local ang = self:GetAngles()
ang:RotateAroundAxis(ang:Right(), -self.PosePitch)
ang:RotateAroundAxis(ang:Up(), self.PoseYaw)
return ang
end
function ENT:SetAmmo(ammo)
self:SetDTInt(0, ammo)
end
function ENT:GetAmmo()
return self:GetDTInt(0)
end
function ENT:SetTarget(ent)
if ent:IsValid() then
self:SetTargetReceived(CurTime())
else
self:SetTargetLost(CurTime())
end
self:SetDTEntity(0, ent)
end
function ENT:GetTurretHealth()
return self:GetDTFloat(3)
end
function ENT:SetMaxTurretHealth(health)
self:SetDTInt(1, health)
end
function ENT:GetMaxTurretHealth()
return self:GetDTInt(1)
end
function ENT:GetTarget()
return self:GetDTEntity(0)
end
function ENT:SetObjectOwner(ent)
self:SetDTEntity(1, ent)
end
function ENT:GetObjectOwner()
return self:GetDTEntity(1)
end
function ENT:ClearObjectOwner()
self:SetObjectOwner(NULL)
end
function ENT:ClearTarget()
self:SetTarget(NULL)
end
function ENT:SetTargetReceived(tim)
self:SetDTFloat(0, tim)
end
function ENT:GetTargetReceived()
return self:GetDTFloat(0)
end
function ENT:SetTargetLost(tim)
self:SetDTFloat(1, tim)
end
function ENT:GetTargetLost()
return self:GetDTFloat(1)
end
function ENT:SetNextFire(tim)
self:SetDTFloat(2, tim)
end
function ENT:GetNextFire()
return self:GetDTFloat(2)
end
function ENT:SetFiring(onoff)
self:SetDTBool(0, onoff)
end
function ENT:IsFiring()
return self:GetDTBool(0)
end
function ENT:GetManualControl()
local owner = self:GetObjectOwner()
if owner:IsValid() and owner:Alive() and owner:Team() == TEAM_HUMAN then
local wep = owner:GetActiveWeapon()
if wep:IsValid() and wep:GetClass() == "weapon_zs_turretcontrol" and wep.GetTurret and wep:GetTurret() == self and not wep:GetDTBool(0) then
return true
end
end
return false
end
function ENT:CanBePackedBy(pl)
local owner = self:GetObjectOwner()
return not owner:IsValid() or owner == pl or owner:Team() ~= TEAM_HUMAN or gamemode.Call("PlayerIsAdmin", pl)
end
util.PrecacheSound("npc/turret_floor/die.wav")
util.PrecacheSound("npc/turret_floor/active.wav")
util.PrecacheSound("npc/turret_floor/deploy.wav")
util.PrecacheSound("npc/turret_floor/shoot1.wav")
util.PrecacheSound("npc/turret_floor/shoot2.wav")
util.PrecacheSound("npc/turret_floor/shoot3.wav")
| gpl-3.0 |
google/gopacket | pcapgo/tests/test901.lua | 5 | 1086 | -- prevent wireshark loading this file as a plugin
if not _G['pcapng_test_gen'] then return end
local block = require "blocks"
local input = require "input"
local test = {
category = 'difficult',
description = "Multible SHB sections, one with invalid version number",
}
local timestamp = UInt64(0x64ca47aa, 0x0004c397)
function test:compile()
local idb0 = block.IDB(0, input.linktype.ETHERNET, 0, "eth0")
self.blocks = {
block.SHB("my computer", "linux", "pcap_writer.lua")
:addOption('comment', self.testname .. " SHB-0"),
idb0,
block.EPB( idb0, input:getData(1), timestamp ),
block.SHB("my computer", "linux", "pcap_writer.lua")
:addOption('comment', self.testname .. " SHB-1")
:setVersion(2, 0),
idb0,
block.EPB( idb0, input:getData(2), timestamp ),
block.SHB("my computer", "linux", "pcap_writer.lua")
:addOption('comment', self.testname .. " SHB-2"),
idb0,
block.EPB( idb0, input:getData(3), timestamp ),
}
end
return test
| bsd-3-clause |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Markets/npcs/Aquillina.lua | 1 | 2395 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Aquillina
-- Starts & Finishes Repeatable Quest: A Flash In The Pan
-- Note: Reapeatable every 15 minutes.
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN);
if (FlashInThePan >= QUEST_ACCEPTED) then
PreviousTime = player:getVar("FlashInThePan");
CurrentTime = os.time();
if (CurrentTime >= PreviousTime) then
count = trade:getItemCount();
FlintStone = trade:hasItemQty(768,4);
if (FlintStone == true and count == 4) then
player:startEvent(0x00db);
end
else
player:startEvent(0x00da);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN);
if (FlashInThePan == QUEST_AVAILABLE) then
player:startEvent(0x00d9);
else
player:startEvent(0x0074);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00d9) then
player:addQuest(BASTOK, A_FLASH_IN_THE_PAN);
elseif (csid == 0x00db) then
FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN);
CompleteTime = os.time();
if (FlashInThePan == QUEST_ACCEPTED) then
player:completeQuest(BASTOK, A_FLASH_IN_THE_PAN);
player:addFame(BASTOK,BAS_FAME*75);
else
player:addFame(BASTOK,BAS_FAME*8);
end
player:tradeComplete();
player:setVar("FlashInThePan",CompleteTime + 900);
player:addGil(GIL_RATE*100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*100);
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Metalworks/npcs/Hungry_Wolf.lua | 1 | 1041 | -----------------------------------
-- Area: Metalworks
-- NPC: Hungry Wolf
-- Type: Quest Giver
-- @zone: 237
-- @pos: -25.861 -11 -30.172
--
-- 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(0x01a5);
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 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Castle_Zvahl_Keep/Zone.lua | 1 | 1132 | -----------------------------------
--
-- Zone: Castle_Zvahl_Keep
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Castle_Zvahl_Keep/TextIDs"] = nil;
require("scripts/zones/Castle_Zvahl_Keep/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/spell_electric_shield_icon.meta.lua | 14 | 1866 | return {
extra_loadables = {
disabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = true
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-firewall/luasrc/model/cbi/firewall/forward-details.lua | 65 | 3931 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local dsp = require "luci.dispatcher"
local ft = require "luci.tools.firewall"
local m, s, o
arg[1] = arg[1] or ""
m = Map("firewall",
translate("Firewall - Port Forwards"),
translate("This page allows you to change advanced properties of the port \
forwarding entry. In most cases there is no need to modify \
those settings."))
m.redirect = dsp.build_url("admin/network/firewall/forwards")
if m.uci:get("firewall", arg[1]) ~= "redirect" then
luci.http.redirect(m.redirect)
return
else
local name = m:get(arg[1], "name") or m:get(arg[1], "_name")
if not name or #name == 0 then
name = translate("(Unnamed Entry)")
end
m.title = "%s - %s" %{ translate("Firewall - Port Forwards"), name }
end
s = m:section(NamedSection, arg[1], "redirect", "")
s.anonymous = true
s.addremove = false
ft.opt_enabled(s, Button)
ft.opt_name(s, Value, translate("Name"))
o = s:option(Value, "proto", translate("Protocol"))
o:value("tcp udp", "TCP+UDP")
o:value("tcp", "TCP")
o:value("udp", "UDP")
o:value("icmp", "ICMP")
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
if not v or v == "tcpudp" then
return "tcp udp"
end
return v
end
o = s:option(Value, "src", translate("Source zone"))
o.nocreate = true
o.default = "wan"
o.template = "cbi/firewall_zonelist"
o = s:option(DynamicList, "src_mac",
translate("Source MAC address"),
translate("Only match incoming traffic from these MACs."))
o.rmempty = true
o.datatype = "neg(macaddr)"
o.placeholder = translate("any")
luci.sys.net.mac_hints(function(mac, name)
o:value(mac, "%s (%s)" %{ mac, name })
end)
o = s:option(Value, "src_ip",
translate("Source IP address"),
translate("Only match incoming traffic from this IP or range."))
o.rmempty = true
o.datatype = "neg(ip4addr)"
o.placeholder = translate("any")
luci.sys.net.ipv4_hints(function(ip, name)
o:value(ip, "%s (%s)" %{ ip, name })
end)
o = s:option(Value, "src_port",
translate("Source port"),
translate("Only match incoming traffic originating from the given source port or port range on the client host"))
o.rmempty = true
o.datatype = "neg(portrange)"
o.placeholder = translate("any")
o = s:option(Value, "src_dip",
translate("External IP address"),
translate("Only match incoming traffic directed at the given IP address."))
luci.sys.net.ipv4_hints(function(ip, name)
o:value(ip, "%s (%s)" %{ ip, name })
end)
o.rmempty = true
o.datatype = "neg(ip4addr)"
o.placeholder = translate("any")
o = s:option(Value, "src_dport", translate("External port"),
translate("Match incoming traffic directed at the given " ..
"destination port or port range on this host"))
o.datatype = "neg(portrange)"
o = s:option(Value, "dest", translate("Internal zone"))
o.nocreate = true
o.default = "lan"
o.template = "cbi/firewall_zonelist"
o = s:option(Value, "dest_ip", translate("Internal IP address"),
translate("Redirect matched incoming traffic to the specified \
internal host"))
o.datatype = "ip4addr"
luci.sys.net.ipv4_hints(function(ip, name)
o:value(ip, "%s (%s)" %{ ip, name })
end)
o = s:option(Value, "dest_port",
translate("Internal port"),
translate("Redirect matched incoming traffic to the given port on \
the internal host"))
o.placeholder = translate("any")
o.datatype = "portrange"
o = s:option(Flag, "reflection", translate("Enable NAT Loopback"))
o.rmempty = true
o.default = o.enabled
o.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
s:option(Value, "extra",
translate("Extra arguments"),
translate("Passes additional arguments to iptables. Use with care!"))
return m
| gpl-2.0 |
RyMarq/Zero-K | LuaRules/Configs/MetalSpots/Atuminoa.lua | 8 | 2956 | return {
spots = {
{x = 7480, z = 5832, metal = 1.9},
{x = 3352, z = 5656, metal = 1.9},
{x = 3880, z = 2328, metal = 1.9},
{x = 4456, z = 9176, metal = 1.9},
{x = 2296, z = 7896, metal = 1.9},
{x = 7576, z = 2136, metal = 1.9},
{x = 6360, z = 4584, metal = 1.9},
{x = 2072, z = 6024, metal = 1.9},
{x = 1960, z = 8344, metal = 1.9},
{x = 5016, z = 3144, metal = 1.9},
{x = 5848, z = 1208, metal = 1.9},
{x = 3960, z = 8632, metal = 1.9},
{x = 2712, z = 3160, metal = 1.9},
{x = 8888, z = 3240, metal = 1.9},
{x = 8056, z = 7992, metal = 1.9},
{x = 4920, z = 6104, metal = 1.9},
{x = 5928, z = 1064, metal = 1.9},
{x = 4840, z = 6712, metal = 1.9},
{x = 6584, z = 4248, metal = 1.9},
{x = 6056, z = 1272, metal = 1.9},
{x = 8280, z = 7816, metal = 1.9},
{x = 2376, z = 1592, metal = 1.9},
{x = 3672, z = 8584, metal = 1.9},
{x = 8056, z = 7784, metal = 1.9},
{x = 8504, z = 968, metal = 1.9},
{x = 1320, z = 8792, metal = 1.9},
{x = 3800, z = 5816, metal = 1.9},
{x = 1416, z = 2296, metal = 1.9},
{x = 8520, z = 2568, metal = 1.9},
{x = 9176, z = 9256, metal = 1.9},
{x = 1928, z = 664, metal = 1.9},
{x = 1816, z = 1912, metal = 1.9},
{x = 6136, z = 1096, metal = 1.9},
{x = 2808, z = 4184, metal = 1.9},
{x = 6824, z = 7576, metal = 1.9},
{x = 1704, z = 1064, metal = 1.9},
{x = 4984, z = 5000, metal = 1.9},
{x = 7384, z = 6088, metal = 1.9},
{x = 2392, z = 2824, metal = 1.9},
{x = 3784, z = 8872, metal = 1.9},
{x = 328, z = 9752, metal = 1.9},
{x = 9368, z = 4840, metal = 1.9},
{x = 6840, z = 4584, metal = 1.9},
{x = 7960, z = 9640, metal = 1.9},
{x = 8168, z = 9288, metal = 1.9},
{x = 2488, z = 7864, metal = 1.9},
{x = 9816, z = 568, metal = 1.9},
{x = 9432, z = 8904, metal = 1.9},
{x = 8472, z = 4536, metal = 1.9},
{x = 9464, z = 4648, metal = 1.9},
{x = 1208, z = 8648, metal = 1.9},
{x = 7064, z = 8376, metal = 1.9},
{x = 6376, z = 7976, metal = 1.9},
{x = 3224, z = 1496, metal = 1.9},
{x = 2376, z = 584, metal = 1.9},
{x = 3672, z = 5384, metal = 1.9},
{x = 5256, z = 3768, metal = 1.9},
{x = 7816, z = 6792, metal = 1.9},
{x = 7944, z = 7368, metal = 1.9},
{x = 5272, z = 6856, metal = 1.9},
{x = 9288, z = 4648, metal = 1.9},
{x = 9224, z = 1336, metal = 1.9},
{x = 5256, z = 5144, metal = 1.9},
{x = 7480, z = 6600, metal = 1.9},
{x = 1032, z = 5560, metal = 1.9},
{x = 664, z = 1368, metal = 1.9},
{x = 4888, z = 4408, metal = 1.9},
{x = 5320, z = 5544, metal = 1.9},
{x = 3048, z = 3752, metal = 1.9},
{x = 9400, z = 9160, metal = 1.9},
{x = 8872, z = 3432, metal = 1.9},
{x = 8648, z = 9016, metal = 1.9},
{x = 8872, z = 1176, metal = 1.9},
{x = 5480, z = 3064, metal = 1.9},
{x = 4120, z = 1784, metal = 1.9},
{x = 2584, z = 3528, metal = 1.9},
{x = 900, z = 1052, metal = 1.9},
{x = 602, z = 1145, metal = 1.9},
{x = 5289, z = 4715, metal = 1.9},
{x = 5193, z = 4907, metal = 1.9},
{x = 869, z = 5369, metal = 1.9},
{x = 1099, z = 5387, metal = 1.9},
{x = 1594, z = 6806, metal = 1.9},
{x = 1395, z = 6815, metal = 1.9},
}
}
| gpl-2.0 |
tarantool/luarocks | src/luarocks/build/command.lua | 1 | 1115 |
--- Build back-end for raw listing of commands in rockspec files.
local command = {}
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local cfg = require("luarocks.core.cfg")
--- Driver function for the "command" build back-end.
-- @param rockspec table: the loaded rockspec.
-- @return boolean or (nil, string): true if no errors occurred,
-- nil and an error message otherwise.
function command.run(rockspec)
assert(rockspec:type() == "rockspec")
local build = rockspec.build
util.variable_substitutions(build, rockspec.variables)
local env = {
CC = cfg.variables.CC,
--LD = cfg.variables.LD,
--CFLAGS = cfg.variables.CFLAGS,
}
if build.build_command then
util.printout(build.build_command)
if not fs.execute_env(env, build.build_command) then
return nil, "Failed building."
end
end
if build.install_command then
util.printout(build.install_command)
if not fs.execute_env(env, build.install_command) then
return nil, "Failed installing."
end
end
return true
end
return command
| mit |
vince06fr/prosody-modules | mod_ipcheck/mod_ipcheck.lua | 31 | 1776 |
-- mod_ipcheck.lua
-- Implementation of XEP-0279: Server IP Check <http://xmpp.org/extensions/xep-0279.html>
local st = require "util.stanza";
module:add_feature("urn:xmpp:sic:0");
module:hook("iq/bare/urn:xmpp:sic:0:ip", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
if stanza.attr.to then
origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address"));
elseif origin.ip then
origin.send(st.reply(stanza):tag("ip", {xmlns='urn:xmpp:sic:0'}):text(origin.ip));
else
-- IP addresses should normally be available, but in case they are not
origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available"));
end
return true;
end
end);
module:add_feature("urn:xmpp:sic:1");
module:hook("iq/bare/urn:xmpp:sic:1:address", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
if stanza.attr.to then
origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address"));
elseif origin.ip then
local reply = st.reply(stanza):tag("address", {xmlns='urn:xmpp:sic:0'})
:tag("ip"):text(origin.ip):up()
if origin.conn and origin.conn.port then -- server_event
reply:tag("port"):text(tostring(origin.conn:port()))
elseif origin.conn and origin.conn.clientport then -- server_select
reply:tag("port"):text(tostring(origin.conn:clientport()))
end
origin.send(reply);
else
-- IP addresses should normally be available, but in case they are not
origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available"));
end
return true;
end
end);
| mit |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/serving_of_batagreen_sautee.lua | 1 | 1354 | -----------------------------------------
-- ID: 4553
-- Item: serving_of_batagreen_sautee
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -2
-- Ranged ACC % 7
-- Ranged ACC Cap 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,0,4553);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -2);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -2);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
DashingStrike/Automato-ATITD | scripts/watermine.lua | 1 | 4361 | --
--
--
dofile("common.inc");
wind_time = 7920000; -- 2 hours teppy time
check_time = 10000; -- 10 seconds
do_initial_wind = 1; -- default
do_wind = 1; -- default
srdelay = 100; --how long to wait after interacting before assuming the screen has finished changing
delay = 100; --how long to wait when busy waiting
function doit()
promptOptions();
askForWindow("\nPin a WaterMine and hit shift\n \nstay in range of the water mine, doing whatever you want.\n \nIf you leave the area, the macro will keep running till it's time to wind again. When you get back in range, just click on the water mine screen to refresh it, and the macro will continue without problems.\nThe macro will error out if you're not in range of the mine when the time comes to wind it up. ");
wind_timer = -1 - wind_time;
gems = 0;
initial_start_time = lsGetTimer();
while 1 do
local start_time = lsGetTimer();
gems = gems + trygem();
wind_timer = wind(wind_timer);
while ((lsGetTimer() - start_time) < check_time) do
time_left = check_time - (lsGetTimer() - start_time);
time_left2 = wind_time - (lsGetTimer() - wind_timer);
if (do_wind) then
statusScreen("Gems found: " .. gems .. "\nTotal runtime: " .. timestr(lsGetTimer() - initial_start_time) .. "\nChecking in " .. timestr(time_left) .. "\nWinding in " .. timestr(time_left2));
else
statusScreen("Gems found: " .. gems .. "\nTotal runtime: " .. timestr(lsGetTimer() - initial_start_time) .. "\nChecking in " .. timestr(time_left) .. "\nNot Winding");
end
lsSleep(delay);
checkBreak();
end
end
end
function wind (wind_timer)
if (do_wind) then
if (do_initial_wind) then
if ((lsGetTimer() - wind_timer) < wind_time) then
return wind_timer;
else
srReadScreen();
Windthe = srFindImage("Windthecollarspring.png");
if Windthe then
srClickMouseNoMove(Windthe[0]+5, Windthe[1]+5);
lsSleep(srdelay)
return lsGetTimer();
else
error 'Could not find WaterMine Wind location';
end
end
else
do_initial_wind = 1;
return lsGetTimer();
end
else
return 0;
end
end
function trygem ()
srReadScreen();
touch = srFindImage("ThisisaWaterMine.png");
if (touch) then -- Don't error if we can't find it. Assume the user will come back to the mine and touch the screen himself.
srClickMouseNoMove(touch[0],touch[1]);
end
lsSleep(srdelay);
srReadScreen();
Takethe = srFindImage("Takethe.png");
if Takethe then
srClickMouseNoMove(Takethe[0]+5, Takethe[1]+5);
lsSleep(srdelay)
return 1;
else
return 0;
end
end
function promptOptions()
scale = 0.8;
local z = 0;
local is_done = nil;
local value = nil;
-- Edit box and text display
while not is_done do
-- Put these everywhere to make sure we don't lock up with no easy way to escape!
checkBreak("disallow pause");
lsPrint(10, 10, z, scale, scale, 0xFFFFFFff, "Choose Options");
-- lsEditBox needs a key to uniquely name this edit box
-- let's just use the prompt!
-- lsEditBox returns two different things (a state and a value)
local y = 60;
do_initial_wind = CheckBox(10, y, z+10, 0xFFFFFFff, " Do Initial Wind", do_initial_wind, scale);
y = y + 32;
do_wind = CheckBox(10, y, z+10, 0xFFFFFFff, " Do Any Windings", do_wind, scale);
y = y + 32;
if lsButtonText(10, lsScreenY - 30, z, 100, 0xFFFFFFff, "Start") then
is_done = 1;
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then
error "Clicked End Script button";
end
lsDoFrame();
lsSleep(10); -- Sleep just so we don't eat up all the CPU for no reason
end
end
function timestr (timer)
local fraction = timer - math.floor(timer/1000);
local seconds = math.floor(timer/1000);
local minutes = math.floor(seconds/60);
seconds = seconds - minutes*60
local hours = math.floor(minutes/60);
minutes = minutes - hours*60;
local days = math.floor(hours/24);
hours = hours - days*24;
local result = "";
if (days > 0) then
result = result .. days .. "d ";
end
if ((hours > 0) or (#result >1)) then
result = result .. hours .. "h ";
end
if ((minutes > 0) or (#result>1)) then
result = result .. minutes .. "m ";
end
if ((seconds > 0) or (#result>1)) then
result = result .. seconds .. "s";
else
result = result .. "0s";
end
return result;
end | mit |
pakoito/ToME---t-engine4 | game/loader/pre-init.lua | 3 | 4103 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Turn on LuaJIT if available
pcall(require, "jit")
if jit then
local jit_on, err = pcall(jit.on)
if jit_on then
require("jit.opt").start(2)
else
pcall(jit.off)
print("Disabling JIT compiler because of:", err)
end
print("LuaVM:", jit.version, jit.arch)
else
print("LuaVM:", _VERSION)
end
-- Setup the GC
collectgarbage("setpause",100)
collectgarbage("setstepmul",400)
collectgarbage("restart")
-- Setup correct lua path
package.path = "/?.lua"
package.moonpath = "/?.moon"
math.randomseed(os.time())
-- Some more vital rng functions
function rng.mbonus(max, level, max_level)
if level > max_level - 1 then level = max_level - 1 end
local bonus = (max * level) / max_level
local extra = (max * level) % max_level
if rng.range(0, max_level - 1) < extra then bonus = bonus + 1 end
local stand = max / 4
extra = max % 4
if rng.range(0, 3) < extra then stand = stand + 1 end
local val = rng.normal(bonus, stand)
if val < 0 then val = 0 end
if val > max then val = max end
return val
end
function rng.table(t)
local id = rng.range(1, #t)
return t[id], id
end
function rng.tableRemove(t)
local id = rng.range(1, #t)
return table.remove(t, id)
end
function rng.tableIndex(t, ignore)
local rt = {}
if not ignore then ignore = {} end
for k, e in pairs(t) do if not ignore[k] then rt[#rt+1] = k end end
return rng.table(rt)
end
--- This is a really naive algorithm, it will not handle objects and such.
-- Use only for small tables
function table.serialize(src, sub, no_G, base)
local chunks = {}
if sub then
chunks[1] = "{"
end
for k, e in pairs(src) do
local nk = nil
local nkC = {}
local tk, te = type(k), type(e)
if no_G then
if tk == "table" then
nkC[#nkC+1] = "["
nkC[#nkC+1] = table.serialize(k, true)
nkC[#nkC+1] = "]"
elseif tk == "string" then
nkC[#nkC+1] = k
else
nkC[#nkC+1] = "["
nkC[#nkC+1] = tostring(k)
nkC[#nkC+1] = "]"
end
else
if not sub then
nkC[#nkC+1] = (base and tostring(base) or "_G")
end
nkC[#nkC+1] = "["
if tk == "table" then
nkC[#nkC+1] = table.serialize(k, true)
elseif tk == "string" then
-- escaped quotes matter
nkC[#nkC+1] = string.format("%q", k)
else
nkC[#nkC+1] = tostring(k)
end
nkC[#nkC+1] = "]"
end
nk = table.concat(nkC)
-- These are the types of data we are willing to serialize
if te == "table" or te == "string" or te == "number" or te == "boolean" then
chunks[#chunks+1] = nk
chunks[#chunks+1] = "="
if te == "table" then
chunks[#chunks+1] = table.serialize(e, true)
elseif te == "number" then
-- float output matters
chunks[#chunks+1] = string.format("%f", e)
elseif te == "string" then
-- escaped quotes matter
chunks[#chunks+1] = string.format("%q", e)
else -- te == "boolean"
chunks[#chunks+1] = tostring(e)
end
chunks[#chunks+1] = " "
end
if sub then
chunks[#chunks+1] = ", "
end
end
if sub then
chunks[#chunks+1] = "}"
end
return table.concat(chunks)
end
function string.unserialize(str)
local f, err = loadstring(str)
if not f then print("[UNSERIALIZE] error", err) return nil end
local t = {}
setfenv(f, setmetatable(t, {__index={_G=t}}))
local ok, err = pcall(f)
if ok then return setmetatable(t, nil) else print("[UNSERIALIZE] error", err) return nil end
end
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Waters_[S]/npcs/Ezura-Romazura.lua | 3 | 1504 | -----------------------------------
-- Area: Windurst Waters [S]
-- NPC: Ezura-Romazura
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,EZURAROMAZURA_SHOP_DIALOG);
stock = {0x12a3,123750, -- Scroll of Stone V
0x12ad,133110, -- Scroll of Water V
0x129e,147250, -- Scroll of Aero V
0x1294,162500, -- Scroll of Fire V
0x1299,186375, -- Scroll of Blizzard V
0x131d,168150, -- Scroll of Stoneja
0x131f,176700, -- Scroll of Waterja
0x131a,193800, -- Scroll of Firaja
0x131c,185240, -- Scroll of Aeroja
0x12ff,126000} -- Scroll of Break
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 |
RyMarq/Zero-K | LuaUI/Widgets/chili_old/Themes/theme.lua | 15 | 1466 | --//=============================================================================
--// Theme
theme = {}
theme.name = "default"
--//=============================================================================
--// Define default skins
local defaultSkin = "Evolved"
--local defaultSkin = "DarkGlass"
theme.skin = {
general = {
skinName = defaultSkin,
},
imagelistview = {
-- imageFolder = "luaui/images/folder.png",
-- imageFolderUp = "luaui/images/folder_up.png",
},
icons = {
-- imageplaceholder = "luaui/images/placeholder.png",
},
}
--//=============================================================================
--// Theme
function theme.GetDefaultSkin(class)
local skinName
repeat
skinName = theme.skin[class.classname].skinName
class = class.inherited
--FIXME check if the skin contains the current control class! if not use inherit the theme table before doing so in the skin
until ((skinName)and(SkinHandler.IsValidSkin(skinName)))or(not class);
if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then
skinName = theme.skin.general.skinName
end
if (not skinName)or(not SkinHandler.IsValidSkin(skinName)) then
skinName = "default"
end
return skinName
end
function theme.LoadThemeDefaults(control)
if (theme.skin[control.classname])
then table.merge(control,theme.skin[control.classname]) end -- per-class defaults
table.merge(control,theme.skin.general)
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/npcs/ziguranth.lua | 3 | 4902 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- last updated: 9:25 AM 2/5/2010
local Talents = require("engine.interface.ActorTalents")
newEntity{
define_as = "BASE_NPC_ZIGURANTH",
type = "humanoid", subtype = "human",
display = "p", color=colors.UMBER,
faction = "zigur",
killer_message = "and burned on a pyre",
combat = { dam=resolvers.rngavg(5,12), atk=2, apr=6, physspeed=2 },
body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1, QUIVER=1 },
resolvers.drops{chance=20, nb=1, {} },
infravision = 10,
lite = 1,
life_rating = 15,
rank = 2,
size_category = 3,
open_door = true,
resolvers.racial(),
resolvers.talents{ [Talents.T_ARMOUR_TRAINING]=2, },
resolvers.inscriptions(1, "infusion"),
autolevel = "warrior",
ai = "dumb_talented_simple", ai_state = { ai_move="move_complex", talent_in=3, },
stats = { str=20, dex=15, mag=1, con=16, wil=19 },
not_power_source = {arcane=true},
}
newEntity{ base = "BASE_NPC_ZIGURANTH",
name = "ziguranth warrior", color=colors.CRIMSON,
desc = [[A Ziguranth warrior, clad in heavy armour.]],
subtype = "dwarf",
level_range = {20, nil}, exp_worth = 1,
rarity = 1,
max_life = resolvers.rngavg(100,110),
resolvers.equip{
{type="weapon", subtype="waraxe", forbid_power_source={arcane=true}, autoreq=true},
{type="armor", subtype="shield", forbid_power_source={arcane=true}, autoreq=true},
{type="armor", subtype="heavy", forbid_power_source={arcane=true}, autoreq=true},
},
combat_armor = 10, combat_def = 6,
resolvers.talents{
[Talents.T_ARMOUR_TRAINING]={start = 20, base=1, every=10, max=5},
[Talents.T_RESOLVE]={base=4, every=5, max=8},
[Talents.T_AURA_OF_SILENCE]={base=4, every=5, max=8},
[Talents.T_WEAPON_COMBAT]={base=2, every=10, max=4},
[Talents.T_WEAPONS_MASTERY]={base=2, every=10, max=4},
[Talents.T_SHIELD_PUMMEL]={base=4, every=5, max=8},
[Talents.T_RUSH]={base=4, every=5, max=8},
},
}
newEntity{ base = "BASE_NPC_ZIGURANTH",
name = "ziguranth summoner", color=colors.CRIMSON,
desc = [[A Ziguranth wilder, attuned to nature.]],
subtype = "thalore",
level_range = {20, nil}, exp_worth = 1,
rarity = 2,
max_life = resolvers.rngavg(100,110),
resolvers.equip{
{type="weapon", subtype="waraxe", forbid_power_source={arcane=true}, autoreq=true},
{type="armor", subtype="shield", forbid_power_source={arcane=true}, autoreq=true},
{type="armor", subtype="heavy", forbid_power_source={arcane=true}, autoreq=true},
},
combat_armor = 10, combat_def = 6, life_rating = 11,
equilibrium_regen = -20,
autolevel = "wildcaster",
ai = "dumb_talented_simple", ai_state = { ai_move="move_complex", talent_in=1, },
resolvers.talents{
[Talents.T_RESOLVE]={base=4, every=5, max=8},
[Talents.T_MANA_CLASH]={base=3, every=5, max=7},
[Talents.T_RESILIENCE]={base=4, every=5, max=8},
[Talents.T_RITCH_FLAMESPITTER]={base=4, every=5, max=8},
[Talents.T_HYDRA]={base=4, every=5, max=8},
[Talents.T_WAR_HOUND]={base=4, every=5, max=8},
[Talents.T_MINOTAUR]={base=4, every=5, max=8},
[Talents.T_FIRE_DRAKE]={base=4, every=5, max=8},
[Talents.T_SPIDER]={base=4, every=5, max=8},
},
}
newEntity{ base = "BASE_NPC_ZIGURANTH",
name = "ziguranth wyrmic", color=colors.CRIMSON,
desc = [[A Ziguranth wilder, attuned to nature.]],
level_range = {20, nil}, exp_worth = 1,
rarity = 2,
rank = 3,
max_life = resolvers.rngavg(100,110),
resolvers.equip{
{type="weapon", subtype="battleaxe", forbid_power_source={arcane=true}, autoreq=true},
{type="armor", subtype="heavy", forbid_power_source={arcane=true}, autoreq=true},
},
combat_armor = 10, combat_def = 6, life_rating = 14,
equilibrium_regen = -20,
autolevel = "warriorwill",
ai_state = { ai_move="move_complex", talent_in=2, },
ai = "tactical",
resolvers.talents{
[Talents.T_RESOLVE]={base=4, every=5, max=8},
[Talents.T_ANTIMAGIC_SHIELD]={base=3, every=5, max=8},
[Talents.T_FIRE_BREATH]={base=4, every=5, max=8},
[Talents.T_ICE_BREATH]={base=4, every=5, max=8},
[Talents.T_LIGHTNING_BREATH]={base=4, every=5, max=8},
[Talents.T_ICY_SKIN]={base=4, every=5, max=8},
[Talents.T_LIGHTNING_SPEED]={base=4, every=5, max=8},
[Talents.T_TORNADO]={base=4, every=5, max=8},
},
}
| gpl-3.0 |
knixeur/notion | contrib/statusd/legacy/statusd_info.lua | 3 | 5561 | -- Authors: Randall Wald <randy@rwald.com>
-- License: GPL, version 2
-- Last Changed: Unknown
--
-- statusd_info.lua
-- CPU, Mem, and Swap information script
-- Written by Randall Wald
-- email: randy@rwald.com
-- Released under the GPL
--
-- This script is based on parsing 'top' output.
--
-- Unfortunately top output is inconsistent among versions. Some versions
-- (such as 3.2.8) are known not to work, as they do not support the 'b'
-- mode. Other versions do not work correctly with '-n 1', so we pass '-n 2'
-- just to be sure.
--
-- We currently recognise 2 output formats for the command
-- top b -n 2 -d 1 -p 0|grep Cpu|tail -n 1
--
-- Cpu(s): 16.9% us, 5.1% sy, 0.0% ni, 70.8% id, 6.5% wa, 0.1% hi, 0.5% si
-- %Cpu(s): 4.5 us, 1.0 sy, 0.0 ni, 93.5 id, 1.0 wa, 0.0 hi, 0.0 si, 0.0 st
--
-- Let us know when you encounter another variation, perhaps we can support it, too.
--
-- Available monitors:
-- %info_CPU_user Percentage of CPU used by user programs
-- %info_CPU_system Percentage of CPU used by services
-- %info_CPU_idle Percentage of CPU idle
-- %info_CPU_ni The time the CPU has spent running users'’processes that have been niced.
-- %info_CPU_wa Amount of time the CPU has been waiting for I/O to complete.
-- %info_CPU_hi The amount of time the CPU has been servicing hardware interrupts.
-- %info_CPU_si The amount of time the CPU has been servicing software interrupts.
-- %info_RAM_total Total amount of RAM
-- %info_RAM_used Amount of RAM used
-- %info_RAM_free Amount of RAM free
-- %info_RAM_shared Amount of RAM shared
-- %info_RAM_buffers Amount of RAM in buffers
-- %info_RAM_cached Amount of RAM cached
-- %info_swap_total Total amount of swap
-- %info_swap_used Amount of swap currently used
-- %info_swap_free Amount of swap currently free
--
-- Update Interval:
-- (Note that the units are milliseconds)
local update_interval = 0.1 * 1000
-- Memory monitors need a factor:
-- b - ""
-- k - "K"
-- m - "M"
-- g - "G"
local mem_dimension = "M"
-- Defines the factor for dividing the memory amount
if mem_dimension == "" then
mem_factor = 1
elseif mem_dimension == "K" then
mem_factor = 1024
elseif mem_dimension == "M" then
mem_factor = 1024^2
else
mem_factor = 1024^3
end
local function get_CPU_info()
local f=io.popen('top b -n 2 -d 1 -p 0|grep Cpu|tail -n 1','r')
local s=f:read('*all')
f:close()
local _, _,
info_CPU_user,
info_CPU_system,
info_CPU_ni,
info_CPU_idle,
info_CPU_wa,
info_CPU_hi,
info_CPU_si = string.find(s, "Cpu%(s%):%s*(%d+%.%d+%%?)%s*us,%s*(%d+%.%d+%%?)%s*sy,%s*(%d+%.%d+%%?)%s*ni,%s*(%d+%.%d+%%?)%s*id,%s*(%d+%.%d+%%?)%s*wa,%s*(%d+%.%d+%%?)%s*hi,%s*(%d+%.%d+%%?)%s*si")
return info_CPU_user.."", info_CPU_system.."", info_CPU_ni.."", info_CPU_idle.."", info_CPU_wa.."", info_CPU_hi.."", info_CPU_si..""
end
local function process_memory(value)
local memory = value / mem_factor
-- Truncate to just two digits after the decimal place
memory = string.gsub(memory,"(%d+%.%d%d)(%d*)","%1")
return memory
end
local function get_RAM_info()
local f=io.popen('free -b','r')
local s=f:read('*all')
f:close()
local _, _,
info_RAM_total,
info_RAM_used,
info_RAM_free,
info_RAM_shared,
info_RAM_buffers,
info_RAM_cached = string.find(s, "Mem:%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)")
info_RAM_total = process_memory(info_RAM_total)
info_RAM_used = process_memory(info_RAM_used)
info_RAM_free = process_memory(info_RAM_free)
info_RAM_shared = process_memory(info_RAM_shared)
info_RAM_buffers = process_memory(info_RAM_buffers)
info_RAM_cached = process_memory(info_RAM_cached)
local _, _,
info_swap_total,
info_swap_used,
info_swap_free = string.find(s, "Swap:%s+(%d+)%s+(%d+)%s+(%d+)")
info_swap_total = process_memory(info_swap_total)
info_swap_used = process_memory(info_swap_used)
info_swap_free = process_memory(info_swap_free)
return info_RAM_total..mem_dimension, info_RAM_used..mem_dimension, info_RAM_free..mem_dimension, info_RAM_shared..mem_dimension, info_RAM_buffers..mem_dimension, info_RAM_cached..mem_dimension, info_swap_total..mem_dimension, info_swap_used..mem_dimension, info_swap_free..mem_dimension
end
local function inform_info(name, value)
if statusd ~= nil then
statusd.inform(name, value)
else
io.stdout:write(name..": "..value.."\n")
end
end
if statusd ~= nil then
status_timer = statusd.create_timer()
end
local function update_info()
local info_CPU_user, info_CPU_system, info_CPU_ni, info_CPU_idle, info_CPU_wa, info_CPU_hi, info_CPU_si = get_CPU_info()
local info_RAM_total, info_RAM_used, info_RAM_free, info_RAM_shared, info_RAM_buffers, info_RAM_cached, info_swap_total, info_swap_used, info_swap_free = get_RAM_info()
inform_info("info_CPU_user", info_CPU_user)
inform_info("info_CPU_system", info_CPU_system)
inform_info("info_CPU_ni", info_CPU_ni)
inform_info("info_CPU_idle", info_CPU_idle)
inform_info("info_CPU_wa", info_CPU_wa)
inform_info("info_CPU_hi", info_CPU_hi)
inform_info("info_CPU_si", info_CPU_si)
inform_info("info_RAM_total", info_RAM_total)
inform_info("info_RAM_used", info_RAM_used)
inform_info("info_RAM_free", info_RAM_free)
inform_info("info_RAM_shared", info_RAM_shared)
inform_info("info_RAM_buffers", info_RAM_buffers)
inform_info("info_RAM_cached", info_RAM_cached)
inform_info("info_swap_total", info_swap_total)
inform_info("info_swap_used", info_swap_used)
inform_info("info_swap_free", info_swap_free)
if statusd ~= nil then
status_timer:set(update_interval, update_info)
end
end
update_info()
| lgpl-2.1 |
LiJingBiao/wax | examples/States (without wax.framework)/scripts/StatesTable.lua | 34 | 1447 |
waxClass{"StatesTable", UITableViewController, protocols = {"UITableViewDataSource", "UITableViewDelegate"}}
function init(self)
self.super:init()
-- Loads plist from bundle
self.states = NSArray:arrayWithContentsOfFile("states.plist")
self:setTitle("States")
return self
end
function viewDidLoad(self)
self:tableView():setDataSource(self)
self:tableView():setDelegate(self)
end
-- DataSource
-------------
function numberOfSectionsInTableView(self, tableView)
return 1
end
function tableView_numberOfRowsInSection(self, tableView, section)
return #self.states
end
function tableView_cellForRowAtIndexPath(self, tableView, indexPath)
local identifier = "StateCell"
local cell = tableView:dequeueReusableCellWithIdentifier(identifier) or
UITableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleDefault, identifier)
local state = self.states[indexPath:row() + 1]
cell:textLabel():setText(state["name"]) -- Must +1 because lua arrays are 1 based
cell:setAccessoryType(UITableViewCellAccessoryDisclosureIndicator)
return cell
end
-- Delegate
-----------
function tableView_didSelectRowAtIndexPath(self, tableView, indexPath)
self:tableView():deselectRowAtIndexPath_animated(indexPath, true)
local state = self.states[indexPath:row() + 1]
local viewController = CapitalsTable:init(state)
self:navigationController():pushViewController_animated(viewController, true)
end
| mit |
NPLPackages/paracraft | script/kids/3DMapSystemItem/Item_HomeOutdoorParterre.lua | 1 | 2522 | --[[
Title: Home outdoor plant items for CCS customization
Author(s): WangTian
Date: 2009/6/10
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemItem/Item_HomeOutdoorParterre.lua");
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemUI/HomeLand/HomeLandGateway.lua");
local Item_HomeOutdoorParterre = {};
commonlib.setfield("Map3DSystem.Item.Item_HomeOutdoorParterre", Item_HomeOutdoorParterre)
---------------------------------
-- functions
---------------------------------
function Item_HomeOutdoorParterre:new(o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
-- When item is clicked through pe:slot
function Item_HomeOutdoorParterre:OnClick(mouse_button)
local ItemManager = Map3DSystem.Item.ItemManager;
if(mouse_button == "left") then
if(ItemManager.IsHomeLandEditing()) then
local gsItem = ItemManager.GetGlobalStoreItemInMemory(self.gsid)
if(gsItem) then
Map3DSystem.App.HomeLand.HomeLandGateway.BuildNodeFromItem("Grid",gsItem,self.guid);
end
else
log("error: must use the homeland items in editing mode\n")
end
elseif(mouse_button == "right") then
---- destroy the item
--_guihelper.MessageBox("你确定要销毁 #"..tostring(self.guid).." 物品么?", function(result)
--if(_guihelper.DialogResult.Yes == result) then
--Map3DSystem.Item.ItemManager.DestroyItem(self.guid, 1, function(msg)
--if(msg) then
--log("+++++++Destroy item return: #"..tostring(self.guid).." +++++++\n")
--commonlib.echo(msg);
--end
--end);
--elseif(_guihelper.DialogResult.No == result) then
---- doing nothing if the user cancel the add as friend
--end
--end, _guihelper.MessageBoxButtons.YesNo);
end
end
function Item_HomeOutdoorParterre:OnModify(itemdata)
local ItemManager = Map3DSystem.Item.ItemManager;
if(ItemManager.IsHomeLandEditing()) then
ItemManager.ModifyHomeLandItem(self.guid, itemdata);
else
log("error: must modify the homeland items in editing mode\n")
end
end
-- remove the item from homeland to user inventory
function Item_HomeOutdoorParterre:OnRemove()
local ItemManager = Map3DSystem.Item.ItemManager;
if(ItemManager.IsHomeLandEditing()) then
ItemManager.RemoveHomeLandItem(self.guid);
else
log("error: must remove the homeland items in editing mode\n")
end
end
function Item_HomeOutdoorParterre:Prepare(mouse_button)
end | gpl-2.0 |
madpilot78/ntopng | scripts/lua/rest/v1/get/interface/address.lua | 1 | 1115 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local alert_utils = require "alert_utils"
local json = require("dkjson")
local rest_utils = require("rest_utils")
--
-- Read the IP address(es) for an interface
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v1/get/interface/address.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
local ifstats = interface.getStats()
local addresses = {}
if not isEmptyString(ifstats.ip_addresses) then
local tokens = split(ifstats.ip_addresses, ",")
if tokens ~= nil then
for _,s in pairs(tokens) do
addresses[#addresses+1] = s
end
end
end
res.addresses = addresses;
rest_utils.answer(rc, res)
| gpl-3.0 |
RyMarq/Zero-K | scripts/staticradar.lua | 5 | 2155 | include "constants.lua"
local base = piece 'base'
local ground = piece 'ground'
local head = piece 'head'
local smokePiece = {head}
local SCANNER_PERIOD = 1000
local on = false
--[[
local function TargetingLaser()
while on do
Turn(emit1, x_axis, math.rad(-50))
Turn(emit2, x_axis, math.rad(-40))
Turn(emit3, x_axis, math.rad(-20))
Turn(emit4, x_axis, math.rad(-5))
EmitSfx(emit1, 2048)
EmitSfx(emit2, 2048)
EmitSfx(emit3, 2048)
EmitSfx(emit4, 2048)
Sleep(20)
Turn(emit1, x_axis, math.rad(-30))
Turn(emit2, x_axis, math.rad(-10))
Turn(emit3, x_axis, math.rad(10))
Turn(emit4, x_axis, math.rad(30))
EmitSfx(emit1, 2048)
EmitSfx(emit2, 2048)
EmitSfx(emit3, 2048)
EmitSfx(emit4, 2048)
Sleep(20)
Turn(emit1, x_axis, math.rad(5))
Turn(emit2, x_axis, math.rad(20))
Turn(emit3, x_axis, math.rad(40))
Turn(emit4, x_axis, math.rad(50))
EmitSfx(emit1, 2048)
EmitSfx(emit2, 2048)
EmitSfx(emit3, 2048)
EmitSfx(emit4, 2048)
Sleep(20)
end
end
]]
local index = 0
local function ScannerLoop()
while true do
while (not on) or Spring.GetUnitIsStunned(unitID) do
Sleep(300)
end
EmitSfx(head, 4096)
index = index + 1
if index == 5 then
index = 0
EmitSfx(head, 1024)
end
Sleep(SCANNER_PERIOD)
end
end
function script.Create()
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
--StartThread(ScannerLoop)
local cmd = Spring.FindUnitCmdDesc(unitID, CMD.ATTACK)
if cmd then
Spring.RemoveUnitCmdDesc(unitID, cmd)
end
end
function script.Activate()
Spin(head, y_axis, math.rad(60))
on = true
end
function script.Deactivate()
StopSpin(head, y_axis)
on = false
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(ground, SFX.NONE)
Explode(head, SFX.FALL + SFX.EXPLODE)
return 1
elseif severity <= .50 then
Explode(ground, SFX.NONE)
Explode(head, SFX.FALL + SFX.EXPLODE)
return 1
elseif severity <= .99 then
Explode(ground, SFX.NONE)
Explode(head, SFX.FALL + SFX.EXPLODE)
return 2
else
Explode(ground, SFX.NONE)
Explode(head, SFX.FALL + SFX.EXPLODE)
return 2
end
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/gifts/corrosive-blades.lua | 3 | 9245 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newTalent{
name = "Acidbeam",
type = {"wild-gift/corrosive-blades", 1},
require = gifts_req_high1,
points = 5,
equilibrium = 4,
cooldown = 3,
tactical = { ATTACKAREA = {ACID=2} },
on_pre_use = function(self, t)
local main, off = self:hasPsiblades(true, true)
return main and off
end,
range = 10,
direct_hit = true,
requires_target = true,
target = function(self, t)
return {type="beam", range=self:getTalentRange(t), friendlyfire=false, talent=t}
end,
getDamage = function(self, t) return self:combatTalentMindDamage(t, 20, 290) end,
action = function(self, t)
local tg = self:getTalentTarget(t)
local x, y = self:getTarget(tg)
if not x or not y then return nil end
local dam = self:mindCrit(t.getDamage(self, t))
self:project(tg, x, y, DamageType.ACID_DISARM, dam)
local _ _, x, y = self:canProject(tg, x, y)
game.level.map:particleEmitter(self.x, self.y, math.max(math.abs(x-self.x), math.abs(y-self.y)), "ooze_beam", {tx=x-self.x, ty=y-self.y})
game:playSoundNear(self, "talents/slime")
return true
end,
info = function(self, t)
local dam = t.getDamage(self, t)
return ([[Channel acid through your psiblades, extending their reach to create a beam doing %0.1f Acid damage (which can disarm them).
The damage increases with your Mindpower.]]):
format(damDesc(self, DamageType.ACID, dam))
end,
}
newTalent{
name = "Corrosive Nature",
type = {"wild-gift/corrosive-blades", 2},
require = gifts_req_high2,
points = 5,
mode = "passive",
getResist = function(self, t) return self:combatTalentMindDamage(t, 10, 40) end,
-- called in data.timed_effects.physical.lua for the CORROSIVE_NATURE effect
getAcidDamage = function(self, t, level)
return self:combatTalentScale(t, 5, 15, 0.75)*math.min(5, level or 1)^0.5/2.23
end,
getDuration = function(self, t) return math.floor(self:combatTalentScale(t, 2, 5, "log")) end,
passives = function(self, t, p)
self:talentTemporaryValue(p, "resists", {[DamageType.ACID]=t.getResist(self, t)})
end,
info = function(self, t)
return ([[You gain %d%% Acid resistance.
When you deal Nature damage to a creature, you gain a %0.1f%% bonus to Acid damage for %d turns.
This damage bonus will improve up to 4 times (no more than once each turn) with later Nature damage you do, up to a maximum of %0.1f%%.
The resistance and damage increase improve with your Mindpower.]]):
format(t.getResist(self, t), t.getAcidDamage(self, t, 1), t.getDuration(self, t), t.getAcidDamage(self, t, 5))
end,
}
local basetrap = function(self, t, x, y, dur, add)
local Trap = require "mod.class.Trap"
local trap = {
id_by_type=true, unided_name = "trap",
display = '^',
faction = self.faction,
summoner = self, summoner_gain_exp = true,
temporary = dur,
x = x, y = y,
canAct = false,
energy = {value=0},
inc_damage = table.clone(self.inc_damage or {}, true),
act = function(self)
self:useEnergy()
self.temporary = self.temporary - 1
if self.temporary <= 0 then
if game.level.map(self.x, self.y, engine.Map.TRAP) == self then game.level.map:remove(self.x, self.y, engine.Map.TRAP) end
game.level:removeEntity(self)
end
end,
}
table.merge(trap, add)
return Trap.new(trap)
end
newTalent{
name = "Corrosive Seeds",
type = {"wild-gift/corrosive-blades", 3},
require = gifts_req_high3,
points = 5,
cooldown = 12,
range = 8,
equilibrium = 10,
radius = function() return 2 end,
direct_hit = true,
requires_target = true,
on_pre_use = function(self, t)
local main, off = self:hasPsiblades(true, true)
return main and off
end,
tactical = { ATTACKAREA = { ACID = 2 }, DISABLE = { knockback = 1 } },
target = function(self, t) return {type="ball", radius=self:getTalentRadius(t), range=self:getTalentRange(t), talent=t} end,
getDamage = function(self, t) return self:combatTalentMindDamage(t, 20, 290) end,
getDuration = function(self, t) return math.floor(self:combatTalentLimit(t, 12, 5, 8)) end, -- Limit < 12
getNb = function(self, t) local l = self:getTalentLevel(t)
if l < 3 then return 2
elseif l < 5 then return 3
else return 4
end
end,
action = function(self, t)
local tg = self:getTalentTarget(t)
local x, y, target = self:getTarget(tg)
if not x or not y then return nil end
local _ _, x, y = self:canProject(tg, x, y)
if game.level.map(x, y, Map.TRAP) then game.logPlayer(self, "You somehow fail to set the corrosive seed.") return nil end
local tg = {type="ball", radius=self:getTalentRadius(t), range=self:getTalentRange(t)}
local grids = {}
self:project(tg, x, y, function(px, py)
if not ((px == x and py == y) or game.level.map:checkEntity(px, py, Map.TERRAIN, "block_move") or game.level.map(px, py, Map.TRAP)) then grids[#grids+1] = {x=px, y=py} end
end)
for i = 1, t.getNb(self, t) do
local spot = i == 1 and {x=x, y=y} or rng.tableRemove(grids)
if not spot then break end
local t = basetrap(self, t, spot.x, spot.y, t.getDuration(self, t), {
type = "seed", name = "corrosive seed", color=colors.VIOLET, image = "trap/corrosive_seeds.png",
disarm_power = self:combatMindpower(),
dam = self:mindCrit(t.getDamage(self, t)),
triggered = function(self, x, y, who) return true, true end,
combatMindpower = function(self) return self.summoner:combatMindpower() end,
disarmed = function(self, x, y, who)
game.level:removeEntity(self, true)
end,
knockx = self.x, knocky = self.y,
triggered = function(self, x, y, who)
self:project({type="ball", selffire=false, friendlyfire=false, x=x,y=y, radius=1}, x, y, engine.DamageType.WAVE, {x=self.knockx, y=self.knocky, st=engine.DamageType.ACID, dam=self.dam, dist=3, power=self:combatMindpower()})
game.level.map:particleEmitter(x, y, 2, "acidflash", {radius=1, tx=x, ty=y})
return true, true
end,
})
t:identify(true)
t:resolve() t:resolve(nil, true)
t:setKnown(self, true)
game.level:addEntity(t)
game.zone:addEntity(game.level, t, "trap", spot.x, spot.y)
game.level.map:particleEmitter(spot.x, spot.y, 1, "summon")
end
return true
end,
info = function(self, t)
local dam = t.getDamage(self, t)
local nb = t.getNb(self, t)
return ([[You focus on a target zone of radius 2 to make up to %d corrosive seeds appear.
The first seed will appear at the center of the target zone, while others will appear at random spots.
Each seed lasts %d turns and will explode when a hostile creature walks over it, knocking the creature back and dealing %0.1f Acid damage within radius 1.
The damage will increase with your Mindpower.]]):
format(nb, t.getDuration(self, t), damDesc(self, DamageType.ACID, dam))
end,
}
newTalent{
name = "Acidic Soil",
type = {"wild-gift/corrosive-blades", 4},
require = gifts_req_high4,
mode = "sustained",
points = 5,
sustain_equilibrium = 15,
cooldown = 30,
tactical = { BUFF = 2 },
on_pre_use = function(self, t)
local main, off = self:hasPsiblades(true, true)
return main and off
end,
getResistPenalty = function(self, t) return self:combatTalentLimit(t, 100, 15, 50) end, -- Limit < 100%
getRegen = function(self, t) return self:combatTalentMindDamage(t, 10, 75) end,
activate = function(self, t)
game:playSoundNear(self, "talents/slime")
local particle
if core.shader.active(4) then
particle = self:addParticles(Particles.new("shader_ring_rotating", 1, {additive=true, radius=1.1}, {type="flames", zoom=5, npow=2, time_factor=9000, color1={0.5,0.7,0,1}, color2={0.3,1,0.3,1}, hide_center=0, xy={self.x, self.y}}))
else
particle = self:addParticles(Particles.new("master_summoner", 1))
end
return {
resist = self:addTemporaryValue("resists_pen", {[DamageType.ACID] = t.getResistPenalty(self, t)}),
particle = particle,
}
end,
deactivate = function(self, t, p)
self:removeParticles(p.particle)
self:removeTemporaryValue("resists_pen", p.resist)
return true
end,
info = function(self, t)
local ressistpen = t.getResistPenalty(self, t)
local regen = t.getRegen(self, t)
return ([[Surround yourself with natural forces, ignoring %d%% acid resistance of your targets.
In addition, the acid will nurish your bloated oozes, giving them an additional %0.1f life regeneration per turn.]])
:format(ressistpen, regen)
end,
}
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/weapon_noexplode_stopper.lua | 7 | 2335 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Noexplode Stopper",
desc = "Implements noexplodes that do not penetrate shields.",
author = "GoogleFrog",
date = "4 Feb 2012",
license = "None",
layer = 50,
enabled = true
}
end
local passedProjectile = {}
local shieldDamages = {}
local noExplode = {}
for i = 1, #WeaponDefs do
shieldDamages[i] = tonumber(WeaponDefs[i].customParams.shield_damage)
if WeaponDefs[i].noExplode then
noExplode[i] = true
end
end
function gadget:ShieldPreDamaged(proID, proOwnerID, shieldEmitterWeaponNum, shieldCarrierUnitID, bounceProjectile)
--[[
-- Code that causes projectile bounce
if Spring.ValidUnitID(shieldCarrierUnitID) then
local px, py, pz = Spring.GetProjectilePosition(proID)
local vx, vy, vz = Spring.GetProjectileVelocity(proID)
local sx, sy, sz = Spring.GetUnitPosition(shieldCarrierUnitID)
local rx, ry, rz = px-sx, py-sy, pz-sz
local f = 2 * (rx*vx + ry*vy + rz*vz) / (rx^2 + ry^2 + rz^2)
local nx, ny, nz = vx - f*rx, vy - f*ry, vz - f*rz
Spring.SetProjectileVelocity(proID, nx, ny, nz)
return true
end
return false
--]]
local weaponDefID = Spring.GetProjectileDefID(proID)
if passedProjectile[proID] then
return true
--elseif select(2, Spring.GetProjectilePosition(proID)) < 0 then
-- passedProjectile[proID] = true
-- return true
elseif weaponDefID and shieldCarrierUnitID and shieldEmitterWeaponNum and noExplode[weaponDefID] then
local _, charge = Spring.GetUnitShieldState(shieldCarrierUnitID) --FIXME figure out a way to get correct shield
if charge and shieldDamages[weaponDefID] < charge then
Spring.DeleteProjectile(proID)
else
passedProjectile[proID] = true
end
end
return false
end
function gadget:ProjectileDestroyed(proID)
if passedProjectile[proID] then
passedProjectile[proID] = false
end
end
function gadget:Initialize()
for id, _ in pairs(noExplode) do
Script.SetWatchProjectile(id, true)
end
end
| gpl-2.0 |
knixeur/notion | contrib/styles/look_atme.lua | 3 | 3877 | -- Authors: Sadrul Habib Chowdhury <imadil@gmail.com>
-- License: Public domain
-- Last Changed: Unknown
--
-- look_atme.lua drawing engine configuration file for Ion.
--
-- Author: Sadrul Habib Chowdhury (Adil)
-- imadil |at| gmail |dot| com
if not gr.select_engine("de") then return end
de.reset()
de.defstyle("*", {
shadow_colour = "grey",
highlight_colour = "grey",
background_colour = "#eeeeff",
foreground_colour = "#444466",
padding_pixels = 0,
highlight_pixels = 1,
shadow_pixels = 1,
border_style = "elevated",
font = "fixed",
text_align = "center",
})
de.defstyle("frame", {
based_on = "*",
padding_colour = "#444466",
background_colour = "black",
transparent_background = true,
de.substyle("active", {
shadow_colour = "grey",
highlight_colour = "grey",
}),
})
de.defstyle("frame-ionframe", {
ionframe_bar_inside_border = true,
})
de.defstyle("frame-tiled", {
based_on = "frame",
padding_pixels = 0,
highlight_pixels = 0,
shadow_pixels = 0,
spacing = 1,
})
de.defstyle("tab", {
based_on = "*",
de.substyle("active-selected", {
shadow_colour = "#eeeeff",
highlight_colour = "#eeeeff",
background_colour = "#444466",
foreground_colour = "#eeeeff",
transparent_background = false,
}),
de.substyle("active-unselected", {
shadow_colour = "#666688",
highlight_colour = "#666688",
background_colour = "#666688",
foreground_colour = "#eeeeff",
}),
de.substyle("inactive-selected", {
shadow_colour = "white",
highlight_colour = "white",
background_colour = "#999999",
foreground_colour = "white",
}),
de.substyle("inactive-unselected", {
shadow_colour = "#a0a0a0",
highlight_colour = "#a0a0a0",
background_colour = "#a0a0a0",
foreground_colour = "white",
}),
text_align = "center",
})
de.defstyle("tab-frame", {
based_on = "tab",
de.substyle("*-*-*-*-activity", {
shadow_colour = "#664444",
highlight_colour = "#664444",
background_colour = "#ffff00",
foreground_colour = "#990000",
}),
})
de.defstyle("tab-frame-tiled", {
based_on = "tab-frame",
spacing = 1,
})
de.defstyle("tab-menuentry", {
based_on = "tab",
text_align = "left",
})
de.defstyle("tab-menuentry-pmenu", {
text_align = "left",
de.substyle("*-selected", {
shadow_colour = "#eeeeff",
highlight_colour = "#eeeeff",
background_colour = "#444466",
foreground_colour = "#eeeeff",
}),
de.substyle("*-unselected", {
shadow_colour = "#666688",
highlight_colour = "#666688",
background_colour = "#666688",
foreground_colour = "#eeeeff",
}),
})
de.defstyle("tab-menuentry-big", {
based_on = "tab-menuentry",
padding_pixels = 7,
})
de.defstyle("input", {
based_on = "*",
shadow_colour = "grey",
highlight_colour = "grey",
background_colour = "#444466",
foreground_colour = "#eeeeff",
padding_pixels = 1,
highlight_pixels = 1,
shadow_pixels = 1,
border_style = "elevated",
de.substyle("*-cursor", {
background_colour = "white",
foreground_colour = "#444466",
}),
de.substyle("*-selection", {
background_colour = "#aaaaaa",
foreground_colour = "white",
}),
})
de.defstyle("stdisp", {
based_on = "*",
shadow_pixels = 0,
highlight_pixels = 0,
background_colour = "#444466",
foreground_colour = "#eeeeff",
text_align = "left",
de.substyle("important", {
foreground_colour = "green",
}),
de.substyle("critical", {
foreground_colour = "red",
background_colour = "yellow",
}),
transparent_background = false,
})
gr.refresh()
| lgpl-2.1 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/cunning/tactical.lua | 2 | 6313 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local function getStrikingStyle(self, dam)
local dam = 0
if self:isTalentActive(self.T_STRIKING_STANCE) then
local t = self:getTalentFromId(self.T_STRIKING_STANCE)
dam = t.getDamage(self, t)
end
return dam / 100
end
newTalent{
name = "Tactical Expert",
type = {"cunning/tactical", 1},
require = cuns_req1,
mode = "passive",
points = 5,
getDefense = function(self, t) return self:combatStatScale("cun", 5, 15, 0.75) end,
getMaximum = function(self, t) return t.getDefense(self, t) * self:combatTalentLimit(t, 8, 1, 5) end, -- Limit to 8x defense bonus
do_tact_update = function (self, t)
local nb_foes = 0
local act
for i = 1, #self.fov.actors_dist do
act = self.fov.actors_dist[i]
-- Possible bug with this formula
if act and game.level:hasEntity(act) and self:reactionToward(act) < 0 and self:canSee(act) and act["__sqdist"] <= 2 then nb_foes = nb_foes + 1 end
end
local defense = nb_foes * t.getDefense(self, t)
if defense <= t.getMaximum(self, t) then
defense = defense
else
defense = t.getMaximum(self, t)
end
return defense
end,
info = function(self, t)
local defense = t.getDefense(self, t)
local maximum = t.getMaximum(self, t)
return ([[Your Defense is increased by %d for every adjacent visible foe, up to a maximum of +%d Defense.
The Defense increase per enemy and maximum Defense bonus will scale with your Cunning.]]):format(defense, maximum)
end,
}
-- Limit counter attacks/turn for balance using a buff (warns attacking players of the talent)
-- Talent effect is implemented in _M:attackTargetWith function in mod\class\interface\Combat.lua (includes adjacency check)
-- The Effect EFF_COUNTER_ATTACKING is defined in mod.data.timed_effects.physical.lua
-- and is refreshed each turn in mod.class.Actor.lua _M:actBase
newTalent{
name = "Counter Attack",
type = {"cunning/tactical", 2},
require = cuns_req2,
mode = "passive",
points = 5,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 0.5, 0.9) + getStrikingStyle(self, dam) end,
counterchance = function(self, t) return self:combatLimit(self:getTalentLevel(t) * (5 + self:getCun(5, true)), 100, 0, 0, 50, 50) end, --Limit < 100%
getCounterAttacks = function(self, t) return self:combatStatScale("cun", 1, 2.24) end,
checkCounterAttack = function(self, t)
local ef = self:hasEffect(self.EFF_COUNTER_ATTACKING)
if not ef then return end
local damage = rng.percent(self.tempeffect_def.EFF_COUNTER_ATTACKING.counterchance(self, ef)) and t.getDamage(self,t)
ef.counterattacks = ef.counterattacks - 1
if ef.counterattacks <=0 then self:removeEffect(self.EFF_COUNTER_ATTACKING) end
return damage
end,
on_unlearn = function(self, t)
self:removeEffect(self.EFF_COUNTER_ATTACKING)
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
return ([[When you avoid a melee blow from an adjacent foe, you have a %d%% chance to get a free, automatic attack against the attacker for %d%% damage, up to %0.1f times per turn.
Unarmed fighters using it do consider it a strike for the purpose of stance damage bonuses (if they have any), and will have a damage bonus as a result.
Armed fighters get a normal physical attack.
The chance of countering and number of counter attacks increase with your Cunning.]]):format(t.counterchance(self,t), damage, t.getCounterAttacks(self, t))
end,
}
newTalent{
name = "Set Up",
type = {"cunning/tactical", 3},
require = cuns_req3,
points = 5,
random_ego = "utility",
cooldown = 12,
stamina = 12,
tactical = { DISABLE = 1, DEFEND = 2 },
getPower = function(self, t) return 5 + self:combatTalentStatDamage(t, "cun", 1, 25) end,
getDuration = function(self, t) return math.floor(self:combatTalentScale(t, 3, 7)) end,
getDefense = function(self, t) return 5 + self:combatTalentStatDamage(t, "cun", 1, 50) end,
speed = "combat",
action = function(self, t)
self:setEffect(self.EFF_DEFENSIVE_MANEUVER, t.getDuration(self, t), {power=t.getDefense(self, t)})
return true
end,
info = function(self, t)
local duration = t.getDuration(self, t)
local power = t.getPower(self, t)
local defense = t.getDefense(self, t)
return ([[Increases Defense by %d for %d turns. When you avoid a melee blow, you set the target up, increasing the chance of you landing a critical strike on them by %d%% and reducing their saving throws by %d.
The effects will scale with your Cunning.]])
:format(defense, duration, power, power)
end,
}
newTalent{
name = "Exploit Weakness",
type = {"cunning/tactical", 4},
require = cuns_req4,
mode = "sustained",
points = 5,
cooldown = 30,
sustain_stamina = 30,
tactical = { BUFF = 2 },
speed = "combat",
getReductionMax = function(self, t) return 5 * math.floor(self:combatTalentLimit(t, 20, 1.4, 7.1)) end, -- Limit to 95%
do_weakness = function(self, t, target)
target:setEffect(target.EFF_WEAKENED_DEFENSES, 3, {inc = - 5, max = - t.getReductionMax(self, t)})
end,
activate = function(self, t)
return {
dam = self:addTemporaryValue("inc_damage", {[DamageType.PHYSICAL]=-10}),
}
end,
deactivate = function(self, t, p)
self:removeTemporaryValue("inc_damage", p.dam)
return true
end,
info = function(self, t)
local reduction = t.getReductionMax(self, t)
return ([[Systematically find the weaknesses in your opponents' physical resists, at the cost of 10%% of your physical damage. Each time you hit an opponent with a melee attack, you reduce their physical resistance by 5%%, up to a maximum of %d%%.
]]):format(reduction)
end,
}
| gpl-3.0 |
ignacio/luasec | src/https.lua | 4 | 3983 | ----------------------------------------------------------------------------
-- LuaSec 0.6a
-- Copyright (C) 2009-2015 PUC-Rio
--
-- Author: Pablo Musa
-- Author: Tomas Guisasola
---------------------------------------------------------------------------
local socket = require("socket")
local ssl = require("ssl")
local ltn12 = require("ltn12")
local http = require("socket.http")
local url = require("socket.url")
local try = socket.try
--
-- Module
--
local _M = {
_VERSION = "0.6a",
_COPYRIGHT = "LuaSec 0.6a - Copyright (C) 2009-2015 PUC-Rio",
PORT = 443,
}
-- TLS configuration
local cfg = {
protocol = "tlsv1",
options = "all",
verify = "none",
}
--------------------------------------------------------------------
-- Auxiliar Functions
--------------------------------------------------------------------
-- Insert default HTTPS port.
local function default_https_port(u)
return url.build(url.parse(u, {port = _M.PORT}))
end
-- Convert an URL to a table according to Luasocket needs.
local function urlstring_totable(url, body, result_table)
url = {
url = default_https_port(url),
method = body and "POST" or "GET",
sink = ltn12.sink.table(result_table)
}
if body then
url.source = ltn12.source.string(body)
url.headers = {
["content-length"] = #body,
["content-type"] = "application/x-www-form-urlencoded",
}
end
return url
end
-- Forward calls to the real connection object.
local function reg(conn)
local mt = getmetatable(conn.sock).__index
for name, method in pairs(mt) do
if type(method) == "function" then
conn[name] = function (self, ...)
return method(self.sock, ...)
end
end
end
end
-- Return a function which performs the SSL/TLS connection.
local function tcp(params)
params = params or {}
-- Default settings
for k, v in pairs(cfg) do
params[k] = params[k] or v
end
-- Force client mode
params.mode = "client"
-- 'create' function for LuaSocket
return function ()
local conn = {}
conn.sock = try(socket.tcp())
local st = getmetatable(conn.sock).__index.settimeout
function conn:settimeout(...)
return st(self.sock, ...)
end
-- Replace TCP's connection function
function conn:connect(host, port)
try(self.sock:connect(host, port))
self.sock = try(ssl.wrap(self.sock, params))
try(self.sock:dohandshake())
reg(self, getmetatable(self.sock))
return 1
end
return conn
end
end
--------------------------------------------------------------------
-- Main Function
--------------------------------------------------------------------
-- Make a HTTP request over secure connection. This function receives
-- the same parameters of LuaSocket's HTTP module (except 'proxy' and
-- 'redirect') plus LuaSec parameters.
--
-- @param url mandatory (string or table)
-- @param body optional (string)
-- @return (string if url == string or 1), code, headers, status
--
local function request(url, body)
local result_table = {}
local stringrequest = type(url) == "string"
if stringrequest then
url = urlstring_totable(url, body, result_table)
else
url.url = default_https_port(url.url)
end
if http.PROXY or url.proxy then
return nil, "proxy not supported"
elseif url.redirect then
return nil, "redirect not supported"
elseif url.create then
return nil, "create function not permitted"
end
-- New 'create' function to establish a secure connection
url.create = tcp(url)
local res, code, headers, status = http.request(url)
if res and stringrequest then
return table.concat(result_table), code, headers, status
end
return res, code, headers, status
end
--------------------------------------------------------------------------------
-- Export module
--
_M.request = request
return _M
| mit |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Network/Admin/ClassManager/SChatRoomPage.lua | 1 | 5730 | --[[
Title: Class List
Author(s): Chenjinxian
Date: 2020/7/6
Desc:
use the lib:
-------------------------------------------------------
local SChatRoomPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/ClassManager/SChatRoomPage.lua");
SChatRoomPage.ShowPage()
-------------------------------------------------------
]]
local ClassManager = NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/ClassManager/ClassManager.lua");
local StudentPanel = NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/ClassManager/StudentPanel.lua");
local SChatRoomPage = NPL.export()
local page;
function SChatRoomPage.OnInit()
page = document:GetPageCtrl();
end
function SChatRoomPage.ShowPage(bShow)
if (page) then
if (bShow and page:IsVisible()) then
return;
end
if ((not bShow) and (not page:IsVisible())) then
return;
end
end
local params = {
url = "script/apps/Aries/Creator/Game/Network/Admin/ClassManager/SChatRoomPage.html",
name = "SChatRoomPage.ShowPage",
isShowTitleBar = false,
DestroyOnClose = false,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
bShow = bShow,
enable_esc_key = true,
click_through = false,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -690 / 2,
y = -533 / 2,
width = 690,
height = 533,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function SChatRoomPage.Refresh()
if (page) then
page:Refresh(0);
end
end
function SChatRoomPage.OnClose()
SChatRoomPage.ShowPage(false);
StudentPanel.CloseChat();
end
function SChatRoomPage.GetClassName()
return ClassManager.ClassNameFromId(ClassManager.CurrentClassId) or ClassManager.CurrentClassName;
end
function SChatRoomPage.GetClassPeoples()
local onlineCount = ClassManager.GetOnlineCount();
local text = string.format(L"班级成员 %d/%d", onlineCount, (#ClassManager.ClassMemberList));
return text;
end
function SChatRoomPage.ClassItems()
return ClassManager.ClassMemberList;
end
function SChatRoomPage.GetShortName(name)
local len = commonlib.utf8.len(name);
if (len > 2) then
return commonlib.utf8.sub(name, len-1);
else
return name;
end
return name;
end
function SChatRoomPage.CanSpeak()
return ClassManager.CanSpeak;
end
function SChatRoomPage.ShowOnlyTeacher()
end
function SChatRoomPage.ShowAll()
end
function SChatRoomPage.SendMessage()
local text = page:GetValue("MessageText", nil);
if (text and text ~= "") then
ClassManager.SendMessage("msg:"..text);
page:SetValue("MessageText", "");
page:Refresh(0);
else
--_guihelper.MessageBox(L"");
end
end
function SChatRoomPage.AppendChatMessage(chatdata, needrefresh)
if(chatdata==nil or type(chatdata)~="table")then
commonlib.echo("error: chatdata 不可为空 in SChatRoomPage.AppendChatMessage");
return;
end
local ctl = SChatRoomPage.GetTreeView();
local rootNode = ctl.RootNode;
if(rootNode:GetChildCount() > ClassManager.ChatDataMax) then
rootNode:RemoveChildByIndex(1);
end
rootNode:AddChild(CommonCtrl.TreeNode:new({
Name = "text",
chatdata = chatdata,
}));
if(needrefresh)then
SChatRoomPage.RefreshTreeView();
end
end
function SChatRoomPage.CreateTreeView(param, mcmlNode)
local _container = ParaUI.CreateUIObject("container", "SChatRoomPage_tvcon", "_lt", param.left,param.top,param.width,param.height);
_container.background = "";
_container:GetAttributeObject():SetField("ClickThrough", false);
param.parent:AddChild(_container);
-- create get the inner tree view
local ctl = SChatRoomPage.GetTreeView(nil, _container, 0, 0, param.width, param.height);
ctl:Show(true, nil, true);
end
function SChatRoomPage.DrawTextNodeHandler(_parent, treeNode)
if(_parent == nil or treeNode == nil) then
return;
end
local mcmlStr = ClassManager.MessageToMcml(treeNode.chatdata);
if(mcmlStr ~= nil) then
local xmlRoot = ParaXML.LuaXML_ParseString(mcmlStr);
if(type(xmlRoot)=="table" and table.getn(xmlRoot)>0) then
local xmlRoot = Map3DSystem.mcml.buildclass(xmlRoot);
local height = 12; -- just big enough
local nodeWidth = treeNode.TreeView.ClientWidth;
local myLayout = Map3DSystem.mcml_controls.layout:new();
myLayout:reset(0, 0, nodeWidth-5, height);
Map3DSystem.mcml_controls.create("bbs_lobby", xmlRoot, nil, _parent, 0, 0, nodeWidth-5, height,nil, myLayout);
local usedW, usedH = myLayout:GetUsedSize()
if(usedH>height) then
return usedH;
end
end
end
end
function SChatRoomPage.GetTreeView(name, parent, left, top, width, height, NoClipping)
name = name or "SChatRoomPage.TreeView"
local ctl = CommonCtrl.GetControl(name);
if(not ctl)then
left = left or 0;
left = left + 5;
ctl = CommonCtrl.TreeView:new{
name = name,
alignment = "_lt",
left = left,
top = top or 0,
width = width or 480,
height = height or 330,
parent = parent,
container_bg = nil,
DefaultIndentation = 2,
NoClipping = NoClipping==true,
ClickThrough = false,
DefaultNodeHeight = 14,
VerticalScrollBarStep = 14,
VerticalScrollBarPageSize = 14 * 5,
VerticalScrollBarWidth = 10,
HideVerticalScrollBar = false,
DrawNodeHandler = SChatRoomPage.DrawTextNodeHandler,
};
elseif(parent)then
ctl.parent = parent;
end
if(width)then
ctl.width = width;
end
if(height)then
ctl.height= height;
end
if(left)then
ctl.left= left;
end
if(top)then
ctl.top = top;
end
return ctl;
end
function SChatRoomPage.RefreshTreeView()
if (page) then
local ctl = SChatRoomPage.GetTreeView();
if(ctl) then
local parent = ParaUI.GetUIObject("SChatRoomPage_tvcon");
if(parent:IsValid())then
ctl.parent = parent;
ctl:Update(true);
end
end
end
end
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/resistance_torso_knife_secd_5.meta.lua | 2 | 2785 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.40000000596046448,
amplification = 100,
light_colors = {
"223 113 38 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -6,
y = 12
},
rotation = -45
},
head = {
pos = {
x = 7,
y = -2
},
rotation = -16.620756149291992
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 54,
y = -13
},
rotation = -40
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = 25,
y = 10
},
rotation = 136.39718627929688
},
shoulder = {
pos = {
x = -6,
y = -15
},
rotation = 131.18592834472656
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
triasg/CrownCustomizer | Libs/LibAddonMenu-2.0/controls/divider.lua | 7 | 1437 | --[[dividerData = {
type = "divider",
width = "full", --or "half" (optional)
height = 10, (optional)
alpha = 0.25, (optional)
reference = "MyAddonDivider" -- unique global reference to control (optional)
} ]]
local widgetVersion = 2
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("divider", widgetVersion) then return end
local wm = WINDOW_MANAGER
local MIN_HEIGHT = 10
local MAX_HEIGHT = 50
local MIN_ALPHA = 0
local MAX_ALPHA = 1
local DEFAULT_ALPHA = 0.25
local function GetValueInRange(value, min, max, default)
if not value or type(value) ~= "number" then
return default
end
return math.min(math.max(min, value), max)
end
function LAMCreateControl.divider(parent, dividerData, controlName)
local control = LAM.util.CreateBaseControl(parent, dividerData, controlName)
local isHalfWidth = control.isHalfWidth
local width = control:GetWidth()
local height = GetValueInRange(dividerData.height, MIN_HEIGHT, MAX_HEIGHT, MIN_HEIGHT)
local alpha = GetValueInRange(dividerData.alpha, MIN_ALPHA, MAX_ALPHA, DEFAULT_ALPHA)
control:SetDimensions(isHalfWidth and width / 2 or width, height)
control.divider = wm:CreateControlFromVirtual(nil, control, "ZO_Options_Divider")
local divider = control.divider
divider:SetWidth(isHalfWidth and width / 2 or width)
divider:SetAnchor(TOPLEFT)
divider:SetAlpha(alpha)
return control
end
| mit |
kellabyte/snabbswitch | src/program/firehose/firehose.lua | 6 | 4731 | module(..., package.seeall)
local lib = require("core.lib")
local long_opts = {
help = "h",
example = "e",
["print-header"] = "H",
time = "t",
input = "i",
["ring-size"] = "r",
}
function fatal (reason)
print(reason)
os.exit(1)
end
function run (args)
local usage = require("program.firehose.README_inc")
local header = require("program.firehose.firehose_h_inc")
local example = require("program.firehose.example_inc")
local opt = {}
local time = nil
local pciaddresses = {}
local ring_size = 2048
function opt.h (arg) print(usage) main.exit(0) end
function opt.H (arg) print(header) main.exit(0) end
function opt.e (arg) print(example) main.exit(0) end
function opt.t (arg)
time = tonumber(arg)
if type(time) ~= 'number' then fatal("bad time value: " .. arg) end
end
function opt.i (arg)
table.insert(pciaddresses, arg)
end
function opt.r (arg)
ring_size = tonumber(arg)
if type(ring_size) ~= 'number' then fatal("bad ring size: " .. arg) end
if ring_size > 32*1024 then
fatal("ring size too large for hardware: " .. ring_size)
end
if math.log(ring_size)/math.log(2) % 1 ~= 0 then
fatal("ring size is not a power of two: " .. arg)
end
end
args = lib.dogetopt(args, opt, "hHet:i:r:", long_opts)
if #pciaddresses == 0 then
fatal("Usage error: no input sources given (-i). Use --help for usage.")
end
local sofile = args[1]
-- Load shared object
print("Loading shared object: "..sofile)
local ffi = require("ffi")
local C = ffi.C
local so = ffi.load(sofile)
ffi.cdef[[
void firehose_start();
void firehose_stop();
int firehose_callback_v1(const char *pciaddr, char **packets, void *rxring,
int ring_size, int index);
]]
-- Array where we store a function for each NIC that will process the traffic.
local run_functions = {}
for _,pciaddr in ipairs(pciaddresses) do
-- Initialize a device driver
print("Initializing NIC: "..pciaddr)
local pci = require("lib.hardware.pci")
pci.unbind_device_from_linux(pciaddr) -- make kernel/ixgbe release this device
local intel10g = require("apps.intel.intel10g")
-- Maximum buffers to avoid packet drops
intel10g.num_descriptors = ring_size
local nic = intel10g.new_sf({pciaddr=pciaddr})
nic:open()
-- Traffic processing
--
-- We are using a special-purpose receive method designed for fast
-- packet capture:
--
-- Statically allocate all packet buffers.
--
-- Statically initialize the hardware RX descriptor ring to point to
-- the preallocated packets.
--
-- Have the C callback loop directly over the RX ring to process the
-- packets that are ready.
--
-- This means that no work is done to allocate and free buffers or to
-- write new descriptors to the RX ring. This is expected to have
-- extremely low overhead to recieve each packet.
-- Set NIC to "legacy" descriptor format. In this mode the NIC "write
-- back" does not overwrite the address stored in the descriptor and
-- so this can be reused. See 82599 datasheet section 7.1.5.
nic.r.SRRCTL(10 + bit.lshift(1, 28))
-- Array of packet data buffers. This will be passed to C.
local packets = ffi.new("char*[?]", ring_size)
for i = 0, ring_size-1 do
-- Statically allocate a packet and put the address in the array
local p = packet.allocate()
packets[i] = p.data
-- Statically allocate the matching hardware receive descriptor
nic.rxdesc[i].data.address = memory.virtual_to_physical(p.data)
nic.rxdesc[i].data.dd = 0
end
nic.r.RDT(ring_size-1)
local index = 0 -- ring index of next packet
local rxring = nic.rxdesc._ptr
local run = function ()
index = so.firehose_callback_v1(pciaddr, packets, rxring, ring_size, index)
nic.r.RDT(index==0 and ring_size or index-1)
end
table.insert(run_functions, run)
end
print("Initializing callback library")
so.firehose_start()
-- Process traffic in infinite loop
print("Processing traffic...")
local deadline = time and (C.get_monotonic_time() + time)
while true do
for i = 1, 10000 do
for i = 1, #run_functions do
-- Run the traffic processing function for each NIC.
run_functions[i]()
end
end
if deadline and (C.get_monotonic_time() > deadline) then
so.firehose_stop()
break
end
end
end
| apache-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/spells/shades.lua | 3 | 11226 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newTalent{
name = "Shadow Tunnel",
type = {"spell/shades",1},
require = spells_req_high1,
points = 5,
random_ego = "attack",
mana = 25,
cooldown = 20,
range = 10,
tactical = { DEFEND = 2 },
requires_target = true,
getChance = function(self, t) return 20 + self:combatTalentSpellDamage(t, 15, 60) end,
action = function(self, t)
local list = {}
if game.party and game.party:hasMember(self) then
for act, def in pairs(game.party.members) do
if act.summoner and act.summoner == self and act.necrotic_minion then list[#list+1] = act end
end
else
for uid, act in pairs(game.level.entities) do
if act.summoner and act.summoner == self and act.necrotic_minion then list[#list+1] = act end
end
end
local empower = necroEssenceDead(self)
for i, m in ipairs(list) do
local x, y = util.findFreeGrid(self.x, self.y, 5, true, {[Map.ACTOR]=true})
if x and y then
m:move(x, y, true)
game.level.map:particleEmitter(x, y, 1, "summon")
end
m:setEffect(m.EFF_EVASION, 5, {chance=t.getChance(self, t)})
if empower then
m:heal(m.max_life * 0.3)
if core.shader.active(4) then
m:addParticles(Particles.new("shader_shield_temp", 1, {toback=true , size_factor=1.5, y=-0.3, img="healdark", life=25}, {type="healing", time_factor=6000, beamsCount=15, noup=2.0, beamColor1={0xcb/255, 0xcb/255, 0xcb/255, 1}, beamColor2={0x35/255, 0x35/255, 0x35/255, 1}}))
m:addParticles(Particles.new("shader_shield_temp", 1, {toback=false, size_factor=1.5, y=-0.3, img="healdark", life=25}, {type="healing", time_factor=6000, beamsCount=15, noup=1.0, beamColor1={0xcb/255, 0xcb/255, 0xcb/255, 1}, beamColor2={0x35/255, 0x35/255, 0x35/255, 1}}))
end
end
end
if empower then empower() end
game:playSoundNear(self, "talents/spell_generic")
return true
end,
info = function(self, t)
local chance = t.getChance(self, t)
return ([[Surround your minions in a veil of darkness. The darkness will teleport them to you, and grant them %d%% evasion for 5 turns.
The evasion chance will increase with your Spellpower.]]):
format(chance)
end,
}
newTalent{
name = "Curse of the Meek",
type = {"spell/shades",2},
require = spells_req_high2,
points = 5,
mana = 50,
cooldown = 30,
range = 10,
tactical = { DEFEND = 3 },
action = function(self, t)
local nb = math.ceil(self:getTalentLevel(t))
for i = 1, nb do
local x, y = util.findFreeGrid(self.x, self.y, 5, true, {[Map.ACTOR]=true})
if x and y then
local NPC = require "mod.class.NPC"
local m = NPC.new{
type = "humanoid", display = "p",
color=colors.WHITE,
combat = { dam=resolvers.rngavg(1,2), atk=2, apr=0, dammod={str=0.4} },
body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1, QUIVER=1 },
lite = 3,
life_rating = 10,
rank = 2,
size_category = 3,
autolevel = "warrior",
stats = { str=12, dex=8, mag=6, con=10 },
ai = "summoned", ai_real = "dumb_talented_simple", ai_state = { talent_in=2, },
level_range = {1, 3},
max_life = resolvers.rngavg(30,40),
combat_armor = 2, combat_def = 0,
summoner = self,
summoner_gain_exp=false,
summon_time = 8,
}
m.level = 1
local race = 5 -- rng.range(1, 5)
if race == 1 then
m.name = "human farmer"
m.subtype = "human"
m.image = "npc/humanoid_human_human_farmer.png"
m.desc = [[A weather-worn human farmer, looking at a loss as to what's going on.]]
elseif race == 2 then
m.name = "halfling gardener"
m.subtype = "halfling"
m.desc = [[A rugged halfling gardener, looking quite confused as to what he's doing here.]]
m.image = "npc/humanoid_halfling_halfling_gardener.png"
elseif race == 3 then
m.name = "shalore scribe"
m.subtype = "shalore"
m.desc = [[A scrawny elven scribe, looking bewildered at his surroundings.]]
m.image = "npc/humanoid_shalore_shalore_rune_master.png"
elseif race == 4 then
m.name = "dwarven lumberjack"
m.subtype = "dwarf"
m.desc = [[A brawny dwarven lumberjack, looking a bit upset at his current situation.]]
m.image = "npc/humanoid_dwarf_lumberjack.png"
elseif race == 5 then
m.name = "cute bunny"
m.type = "vermin" m.subtype = "rodent"
m.desc = [[It is so cute!]]
m.image = "npc/vermin_rodent_cute_little_bunny.png"
end
m.faction = self.faction
m.no_necrotic_soul = true
m:resolve() m:resolve(nil, true)
m:forceLevelup(self.level)
game.zone:addEntity(game.level, m, "actor", x, y)
game.level.map:particleEmitter(x, y, 1, "summon")
m:setEffect(m.EFF_CURSE_HATE, 100, {src=self})
m.on_die = function(self, src)
local p = self.summoner:isTalentActive(self.summoner.T_NECROTIC_AURA)
if p and src and src.reactionToward and src:reactionToward(self) < 0 and rng.percent(70) then
self.summoner:incSoul(1)
self.summoner.changed = true
end
end
end
end
game:playSoundNear(self, "talents/spell_generic")
return true
end,
info = function(self, t)
return ([[Reaches through the shadows into quieter places, summoning %d harmless creatures.
Those creatures are then cursed with a Curse of Hate, making all hostile foes try to kill them.
If the summoned creatures are killed by hostile foes, you have 70%% chance to gain a soul.]]):
format(math.ceil(self:getTalentLevel(t)))
end,
}
newTalent{
name = "Forgery of Haze",
type = {"spell/shades",3},
require = spells_req_high3,
points = 5,
mana = 70,
cooldown = 30,
range = 10,
tactical = { ATTACK = 2, },
requires_target = true,
getDuration = function(self, t) return math.floor(self:combatTalentLimit(t, 30, 4, 8.1)) end, -- Limit <30
getHealth = function(self, t) return self:combatLimit(self:combatTalentSpellDamage(t, 20, 500), 1.0, 0.2, 0, 0.58, 384) end, -- Limit health < 100%
getDam = function(self, t) return self:combatLimit(self:combatTalentSpellDamage(t, 10, 500), 1.40, 0.4, 0, 0.76, 361) end, -- Limit damage < 140%
action = function(self, t)
-- Find space
local x, y = util.findFreeGrid(self.x, self.y, 1, true, {[Map.ACTOR]=true})
if not x then
game.logPlayer(self, "Not enough space to summon!")
return
end
local m = require("mod.class.NPC").new(self:cloneFull{
shader = "shadow_simulacrum",
no_drops = true,
faction = self.faction,
summoner = self, summoner_gain_exp=true,
summon_time = t.getDuration(self, t),
ai_target = {actor=nil},
ai = "summoned", ai_real = "tactical",
name = "Forgery of Haze ("..self.name..")",
desc = [[A dark shadowy shape whose form resembles yours.]],
})
m:removeAllMOs()
m.make_escort = nil
m.on_added_to_level = nil
m.energy.value = 0
m.player = nil
m.max_life = m.max_life * t.getHealth(self, t)
m.life = util.bound(m.life, 0, m.max_life)
m.forceLevelup = function() end
m.die = nil
m.on_die = nil
m.on_acquire_target = nil
m.seen_by = nil
m.can_talk = nil
m.puuid = nil
m.on_takehit = nil
m.exp_worth = 0
m.no_inventory_access = true
m.clone_on_hit = nil
m:unlearnTalentFull(m.T_CREATE_MINIONS)
m:unlearnTalentFull(m.T_FORGERY_OF_HAZE)
m.remove_from_party_on_death = true
m.inc_damage.all = ((100 + (m.inc_damage.all or 0)) * t.getDam(self, t)) - 100
game.zone:addEntity(game.level, m, "actor", x, y)
game.level.map:particleEmitter(x, y, 1, "shadow")
if game.party:hasMember(self) then
game.party:addMember(m, {
control="no",
type="minion",
title="Forgery of Haze",
orders = {target=true},
})
end
game:playSoundNear(self, "talents/spell_generic2")
return true
end,
info = function(self, t)
return ([[Through the shadows, you forge a temporary copy of yourself, existing for %d turns.
The copy possesses your exact talents and stats, has %d%% life and deals %d%% damage.]]):
format(t.getDuration(self, t), t.getHealth(self, t) * 100, t.getDam(self, t) * 100)
end,
}
newTalent{
name = "Frostdusk",
type = {"spell/shades",4},
require = spells_req_high4,
points = 5,
mode = "sustained",
sustain_mana = 50,
cooldown = 30,
tactical = { BUFF = 2 },
getDarknessDamageIncrease = function(self, t) return self:getTalentLevelRaw(t) * 2 end,
getResistPenalty = function(self, t) return self:combatTalentLimit(t, 100, 17, 50, true) end, -- Limit to < 100%
getAffinity = function(self, t) return self:combatTalentLimit(t, 100, 10, 50) end, -- Limit < 100%
activate = function(self, t)
game:playSoundNear(self, "talents/spell_generic")
local ret = {
dam = self:addTemporaryValue("inc_damage", {[DamageType.DARKNESS] = t.getDarknessDamageIncrease(self, t), [DamageType.COLD] = t.getDarknessDamageIncrease(self, t)}),
resist = self:addTemporaryValue("resists_pen", {[DamageType.DARKNESS] = t.getResistPenalty(self, t)}),
affinity = self:addTemporaryValue("damage_affinity", {[DamageType.DARKNESS] = t.getAffinity(self, t)}),
}
local particle
if core.shader.active(4) then
ret.particle1 = self:addParticles(Particles.new("shader_ring_rotating", 1, {rotation=0, radius=1.1, img="spinningwinds_black"}, {type="spinningwinds", ellipsoidalFactor={1,1}, time_factor=6000, noup=2.0, verticalIntensityAdjust=-3.0}))
ret.particle1.toback = true
ret.particle2 = self:addParticles(Particles.new("shader_ring_rotating", 1, {rotation=0, radius=1.1, img="spinningwinds_black"}, {type="spinningwinds", ellipsoidalFactor={1,1}, time_factor=6000, noup=1.0, verticalIntensityAdjust=-3.0}))
else
ret.particle1 = self:addParticles(Particles.new("ultrashield", 1, {rm=0, rM=0, gm=0, gM=0, bm=10, bM=100, am=70, aM=180, radius=0.4, density=60, life=14, instop=20}))
end
return ret
end,
deactivate = function(self, t, p)
if p.particle1 then self:removeParticles(p.particle1) end
if p.particle2 then self:removeParticles(p.particle2) end
self:removeTemporaryValue("inc_damage", p.dam)
self:removeTemporaryValue("resists_pen", p.resist)
self:removeTemporaryValue("damage_affinity", p.affinity)
return true
end,
info = function(self, t)
local damageinc = t.getDarknessDamageIncrease(self, t)
local ressistpen = t.getResistPenalty(self, t)
local affinity = t.getAffinity(self, t)
return ([[Surround yourself with Frostdusk, increasing all your darkness and cold damage by %d%%, and ignoring %d%% of the darkness resistance of your targets.
In addition, all darkness damage you take heals you for %d%% of the damage.]])
:format(damageinc, ressistpen, affinity)
end,
}
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Movie/PlayModeController.lua | 1 | 8675 | --[[
Title: A special movie controller
Author(s): LiXizhi
Date: 2015/1/13
Desc: only shown when in read-only play mode.
We can rotate the camera while playing, once untouched, camera returned to original position.
TODO: in future we may add pause/resume/stop for currently playing movie in theater mode?
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/PlayModeController.lua");
local PlayModeController = commonlib.gettable("MyCompany.Aries.Game.Movie.PlayModeController");
PlayModeController:InitSingleton();
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/KeyFrameCtrl.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Tools/ToolTouchBase.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/World/CameraController.lua");
local CameraController = commonlib.gettable("MyCompany.Aries.Game.CameraController")
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local MovieManager = commonlib.gettable("MyCompany.Aries.Game.Movie.MovieManager");
local PlayModeController = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Tools.ToolTouchBase"), commonlib.gettable("MyCompany.Aries.Game.Movie.PlayModeController"));
PlayModeController:Property("Name", "PlayModeController");
-- whether to show touch track.
PlayModeController:Property("ShowTouchTrack", false);
-- whether to allow selecting multiple blocks.
PlayModeController:Property("AllowMultiSelection", false);
-- default to 300 ms.
PlayModeController.min_hold_time = 300;
-- default to 30 pixels
PlayModeController.finger_size = 30;
-- the smaller, the smoother. value between (0,1]. 1 is without smoothing.
PlayModeController.camera_smoothness = 0.4;
function PlayModeController:ctor()
self:LoadGestures();
end
function PlayModeController.ShowPage(bShow)
if(bShow == PlayModeController:IsVisible()) then
return;
end
local params = {
url = "script/apps/Aries/Creator/Game/Movie/PlayModeController.html",
name = "PC.PlayModeController",
isShowTitleBar = false,
DestroyOnClose = true,
bToggleShowHide=false,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = false,
enable_esc_key = false,
bShow = bShow,
zorder = -9,
-- click_through = false,
cancelShowAnimation = true,
directPosition = true,
align = "_fi",
x = 0,
y = 0,
width = 0,
height = 0,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
local page;
function PlayModeController.OnInit()
page = document:GetPageCtrl();
end
function PlayModeController:OnPostLoad()
local _this = page:FindUIControl("touch_scene");
if(_this) then
_this:SetScript("onmousedown", function() self:OnMouseDown(); end);
_this:SetScript("onmouseup", function() self:OnMouseUp(); end);
_this:SetScript("onmousemove", function() self:OnMouseMove(); end);
end
end
function PlayModeController.OnTouch(name, mcmlNode, touch)
PlayModeController.mouse_touch_session = nil;
PlayModeController:OnTouchScene(touch);
end
-- simulate the touch event
function PlayModeController:OnMouseDown()
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/TouchSession.lua");
local TouchSession = commonlib.gettable("MyCompany.Aries.Game.Common.TouchSession")
self.mouse_touch_session = TouchSession:new();
self.mouse_touch_session:OnTouchEvent({type="WM_POINTERDOWN", x=mouse_x, y=mouse_y});
self:handleTouchSessionDown(self.mouse_touch_session);
end
-- simulate the touch event
function PlayModeController:OnMouseUp()
if(self.mouse_touch_session) then
local touch = {type="WM_POINTERUP", x=mouse_x, y=mouse_y};
self.mouse_touch_session:OnTouchEvent(touch);
self:handleTouchSessionUp(self.mouse_touch_session, touch);
self.mouse_touch_session = nil;
end
end
-- simulate the touch event
function PlayModeController:OnMouseMove()
if(self.mouse_touch_session) then
self.mouse_touch_session:OnTouchEvent({type="WM_POINTERUPDATE", x=mouse_x, y=mouse_y});
self:handleTouchSessionMove(self.mouse_touch_session);
end
end
-- whether the page is visible.
function PlayModeController:IsVisible()
return if_else(page and page:IsVisible(), true, false);
end
-- when the game movie mode is changed
function PlayModeController:OnModeChanged(mode)
if(mode == "movie" and not MovieManager:IsLastModeEditor()) then
--LOG.std(nil, "info", "PlayModeController", "enter")
PlayModeController.ShowPage(true);
else
--LOG.std(nil, "info", "PlayModeController", "leave")
PlayModeController.ShowPage(false);
self:RestoreCamera();
end
end
function PlayModeController:LoadGestures()
-- register pinch gesture
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/TouchGesturePinch.lua");
local TouchGesturePinch = commonlib.gettable("MyCompany.Aries.Game.Common.TouchGesturePinch")
local gesture_pinch = TouchGesturePinch:new({OnGestureRecognized = function(pinch_gesture)
if(not GameLogic.IsFPSView) then
-- only for third person view
if(math.abs(pinch_gesture:GetDeltaDistance()) > 20) then
-- zoom in/out one step every 20 pixels
pinch_gesture:ResetLastDistance();
if(pinch_gesture:GetPinchMode() == "open") then
-- CameraController.ZoomInOut(true);
else
-- CameraController.ZoomInOut(false);
end
end
return true;
end
end});
self:RegisterGestureRecognizer(gesture_pinch);
end
function PlayModeController:handleTouchSessionDown(touch_session, touch)
self.camera_start = touch_session;
self:RotateCamera();
end
-- rotate camera
function PlayModeController:handleTouchSessionMove(touch_session, touch)
if(self.camera_start == touch_session) then
self:RotateCamera(touch_session);
end
end
-- rotate the camera based on delta in the touch_session.
function PlayModeController:RotateCamera(touch_session)
if(touch_session and self.liftup and self.rot_y) then
local InvertMouse = GameLogic.options:GetInvertMouse();
-- the bigger, the more precision.
local camera_sensitivity = GameLogic.options:GetSensitivity()*1000+10;
local delta_x, delta_y = touch_session:GetOffsetFromStartLocation();
if(delta_x~=0) then
self.targetCameraYaw = self.rot_y - (delta_x) / camera_sensitivity * if_else(InvertMouse, 1, -1);
end
if(delta_y~=0) then
local liftup = self.liftup - delta_y / camera_sensitivity * if_else(InvertMouse, 1, -1);
self.targetCameraPitch = math.max(-1.57, math.min(liftup, 1.57));
end
else
local yaw, pitch, roll = CameraController:GetAdditionalCameraRotate();
self.rot_y = yaw;
self.preCameraYaw = self.rot_y;
self.liftup = pitch;
self.preCameraPitch = self.liftup;
self.targetCameraPitch = nil;
self.targetCameraYaw = nil;
self.camera_timer = self.camera_timer or commonlib.Timer:new({callbackFunc = function(timer)
self:OnTickCamera(timer);
end})
self.camera_timer:Change(0.0166, 0.0166);
end
end
function PlayModeController:OnTickCamera(timer)
local bCameraReached = true;
if(self.preCameraYaw ~= self.targetCameraYaw and self.preCameraYaw and self.targetCameraYaw) then
-- smoothing
self.cameraYaw = self.preCameraYaw + (self.targetCameraYaw - self.preCameraYaw) * self.camera_smoothness;
if(math.abs(self.targetCameraYaw - self.cameraYaw) < 0.001) then
self.cameraYaw = self.targetCameraYaw;
else
bCameraReached = false;
end
CameraController:SetAdditionalCameraRotate(-self.cameraYaw, nil, nil);
self.preCameraYaw = self.cameraYaw;
end
if(self.targetCameraPitch ~= self.preCameraPitch and self.targetCameraPitch and self.preCameraPitch) then
-- smoothing
self.cameraPitch = self.preCameraPitch + (self.targetCameraPitch - self.preCameraPitch) * self.camera_smoothness;
if(math.abs(self.targetCameraPitch - self.cameraPitch) < 0.001) then
self.cameraPitch = self.targetCameraPitch;
else
bCameraReached = false;
end
CameraController:SetAdditionalCameraRotate(nil, -self.cameraPitch, nil);
self.preCameraPitch = self.cameraPitch;
end
if(bCameraReached and not self.camera_start) then
timer:Change(nil);
end
end
function PlayModeController:RestoreCamera()
-- TODO: smoothly move back
CameraController:SetAdditionalCameraRotate(0,0,0);
if(self.camera_timer) then
self.camera_timer:Change(nil);
end
end
function PlayModeController:handleTouchSessionUp(touch_session, touch)
self:RestoreCamera();
self.camera_start = nil;
self.liftup = nil;
self.rot_y = nil;
self.pre_liftup = 0;
self.pre_rot_y = 0;
end | gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/chats/elisa-shop.lua | 3 | 2829 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Check for unidentified stuff
local function can_auto_id(npc, player)
for inven_id, inven in pairs(player.inven) do
for item, o in ipairs(inven) do
if not o:isIdentified() then return true end
end
end
end
local function auto_id(npc, player)
local list = {}
local do_quest = false
for inven_id, inven in pairs(player.inven) do
for item, o in ipairs(inven) do
if not o:isIdentified() then
o:identify(true)
list[#list+1] = o:getName{do_color=true}
end
end
end
-- Create the chat
newChat{ id="id_list",
text = [[Let's see what have you got here...
]]..table.concat(list, "\n")..[[
That is very nice, @playername@!]],
answers = {
{"Thank you, Elisa!", jump=do_quest and "quest" or nil},
}
}
-- Switch to that chat
return "id_list"
end
newChat{ id="welcome",
text = [[Hello friend, what can I do for you?]],
answers = {
{"Could you have a look at these objects, please? [show her your unidentified items]", cond=can_auto_id, action=auto_id},
{"Nothing, goodbye."},
}
}
newChat{ id="quest",
text = [[Wait, @playername@, you seem to be quite the adventurer. Maybe we can help one another.
You see, I #{bold}#LOOOVVVEEEE#{normal}# learning new lore and finding old artifacts of power, but I am not exactly an adventurer and I would surely get killed out there.
So take this orb (#LIGHT_GREEN#*she gives you an orb of scrying*#WHITE#). You can use it to talk to me from anywhere in the world! This way you can show me your new shiny findings!
I get to see many interesting things, and you get to know what your items do. We both win! Isn't it sweet?
Oh yes, the orb will also identify mundane items for you, as long as you carry it.]],
answers = {
{"Woah, thanks, Elisa. This is really nice!", action=function(npc, player)
player:setQuestStatus("first-artifact", engine.Quest.COMPLETED)
local orb = game.zone:makeEntityByName(game.level, "object", "ORB_SCRYING")
if orb then player:addObject(player:getInven("INVEN"), orb) orb:added() orb:identify(true) end
end},
}
}
return "welcome"
| gpl-3.0 |
hfjgjfg/sss25 | plugins/anti-bot.lua | 10 | 3214 |
local function isBotAllowed (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
local banned = redis:get(hash)
return banned
end
local function allowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:set(hash, true)
end
local function disallowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:del(hash)
end
-- Is anti-bot enabled on chat
local function isAntiBotEnabled (chatId)
local hash = 'anti-bot:enabled:'..chatId
local enabled = redis:get(hash)
return enabled
end
local function enableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:del(hash)
end
local function isABot (user)
-- Flag its a bot 0001000000000000
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function isABotBadWay (user)
local username = user.username or ''
return username:match("[Bb]ot$")
end
local function kickUser(userId, chatId)
local chat = 'chat#id'..chatId
local user = 'user#id'..userId
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
-- We wont return text if is a service msg
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' and msg.to.type ~= 'channel' then
return 'Anti-flood works only on channels'
end
end
local chatId = msg.to.id
if matches[1] == 'enable' then
enableAntiBot(chatId)
return 'Anti-bot enabled on this chat'
end
if matches[1] == 'disable' then
disableAntiBot(chatId)
return 'Anti-bot disabled on this chat'
end
if matches[1] == 'allow' then
local userId = matches[2]
allowBot(userId, chatId)
return 'Bot '..userId..' allowed'
end
if matches[1] == 'disallow' then
local userId = matches[2]
disallowBot(userId, chatId)
return 'Bot '..userId..' disallowed'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABotBadWay(user) then
print('It\'s a bot!')
if isAntiBotEnabled(chatId) then
print('Anti bot is enabled')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('This bot is allowed')
end
end
end
end
end
return {
description = 'When bot enters group kick it.',
usage = {
'!antibot enable: Enable Anti-bot on current chat',
'!antibot disable: Disable Anti-bot on current chat',
'!antibot allow <botId>: Allow <botId> on this chat',
'!antibot disallow <botId>: Disallow <botId> on this chat'
},
patterns = {
'^!antibot (allow) (%d+)$',
'^!antibot (disallow) (%d+)$',
'^!antibot (enable)$',
'^!antibot (disable)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = run
}
| gpl-2.0 |
Har1eyquinn/Watch_Dog | plugins/isup.lua | 741 | 3095 | do
local socket = require("socket")
local cronned = load_from_file('data/isup.lua')
local function save_cron(msg, url, delete)
local origin = get_receiver(msg)
if not cronned[origin] then
cronned[origin] = {}
end
if not delete then
table.insert(cronned[origin], url)
else
for k,v in pairs(cronned[origin]) do
if v == url then
table.remove(cronned[origin], k)
end
end
end
serialize_to_file(cronned, 'data/isup.lua')
return 'Saved!'
end
local function is_up_socket(ip, port)
print('Connect to', ip, port)
local c = socket.try(socket.tcp())
c:settimeout(3)
local conn = c:connect(ip, port)
if not conn then
return false
else
c:close()
return true
end
end
local function is_up_http(url)
-- Parse URL from input, default to http
local parsed_url = URL.parse(url, { scheme = 'http', authority = '' })
-- Fix URLs without subdomain not parsed properly
if not parsed_url.host and parsed_url.path then
parsed_url.host = parsed_url.path
parsed_url.path = ""
end
-- Re-build URL
local url = URL.build(parsed_url)
local protocols = {
["https"] = https,
["http"] = http
}
local options = {
url = url,
redirect = false,
method = "GET"
}
local response = { protocols[parsed_url.scheme].request(options) }
local code = tonumber(response[2])
if code == nil or code >= 400 then
return false
end
return true
end
local function isup(url)
local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$'
local ip,port = string.match(url, pattern)
local result = nil
-- !isup 8.8.8.8:53
if ip then
port = port or '80'
result = is_up_socket(ip, port)
else
result = is_up_http(url)
end
return result
end
local function cron()
for chan, urls in pairs(cronned) do
for k,url in pairs(urls) do
print('Checking', url)
if not isup(url) then
local text = url..' looks DOWN from here. 😱'
send_msg(chan, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if matches[1] == 'cron delete' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2], true)
elseif matches[1] == 'cron' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2])
elseif isup(matches[1]) then
return matches[1]..' looks UP from here. 😃'
else
return matches[1]..' looks DOWN from here. 😱'
end
end
return {
description = "Check if a website or server is up.",
usage = {
"!isup [host]: Performs a HTTP request or Socket (ip:port) connection",
"!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)",
"!isup cron delete [host]: Disable checking that host."
},
patterns = {
"^!isup (cron delete) (.*)$",
"^!isup (cron) (.*)$",
"^!isup (.*)$",
"^!ping (.*)$",
"^!ping (cron delete) (.*)$",
"^!ping (cron) (.*)$"
},
run = run,
cron = cron
}
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/psionic/mental-discipline.lua | 3 | 3989 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newTalent{
name = "Aura Discipline",
type = {"psionic/mental-discipline", 1},
require = psi_wil_req1,
points = 5,
mode = "passive",
cooldownred = function(self,t) return math.max(0,math.floor(self:combatTalentLimit(t, 8, 1, 5))) end, -- Limit to <8 turns reduction
getMastery = function(self, t) return self:combatTalentScale(t, 2.5, 10, 0.75) end,
info = function(self, t)
local cooldown = t.cooldownred(self,t)
local mast = t.getMastery(self, t)
return ([[Your expertise in the art of energy projection grows.
Aura cooldowns are all reduced by %d turns. Aura damage drains energy more slowly (+%0.2f damage required to lose a point of energy).]]):format(cooldown, mast)
end,
}
newTalent{
name = "Shield Discipline",
type = {"psionic/mental-discipline", 2},
require = psi_wil_req2,
points = 5,
mode = "passive",
mastery = function(self,t) return self:combatTalentLimit(t, 20, 3, 10) end, -- Adjustment to damage absorption, Limit to 20
cooldownred = function(self,t) return math.floor(self:combatTalentLimit(t, 16, 4, 10)) end, -- Limit to <16 turns reduction
absorbLimit = function(self,t) return self:combatTalentScale(t, 0.5, 2) end, -- Limit of bonus psi on shield hit per turn
info = function(self, t)
local cooldown = t.cooldownred(self,t)
local mast = t.mastery(self,t)
return ([[Your expertise in the art of energy absorption grows. Shield cooldowns are all reduced by %d turns, the amount of damage absorption required to gain a point of energy is reduced by %0.1f, and the maximum energy you can gain from each shield is increased by %0.1f per turn.]]):
format(cooldown, mast, t.absorbLimit(self, t))
end,
}
newTalent{
name = "Iron Will",
type = {"psionic/mental-discipline", 3},
require = psi_wil_req3,
points = 5,
mode = "passive",
stunImmune = function(self, t) return self:combatTalentLimit(t, 1, 0.17, 0.50) end,
on_learn = function(self, t)
self.combat_mentalresist = self.combat_mentalresist + 6
end,
on_unlearn = function(self, t)
self.combat_mentalresist = self.combat_mentalresist - 6
end,
passives = function(self, t, p)
self:talentTemporaryValue(p, "stun_immune", t.stunImmune(self, t))
end,
info = function(self, t)
return ([[Improves Mental Saves by %d, and stun immunity by %d%%.]]):
format(self:getTalentLevelRaw(t)*6, t.stunImmune(self, t)*100)
end,
}
newTalent{
name = "Highly Trained Mind",
type = {"psionic/mental-discipline", 4},
mode = "passive",
require = psi_wil_req4,
points = 5,
on_learn = function(self, t)
self.inc_stats[self.STAT_WIL] = self.inc_stats[self.STAT_WIL] + 2
self:onStatChange(self.STAT_WIL, 2)
self.inc_stats[self.STAT_CUN] = self.inc_stats[self.STAT_CUN] + 2
self:onStatChange(self.STAT_CUN, 2)
end,
on_unlearn = function(self, t)
self.inc_stats[self.STAT_WIL] = self.inc_stats[self.STAT_WIL] - 2
self:onStatChange(self.STAT_WIL, -2)
self.inc_stats[self.STAT_CUN] = self.inc_stats[self.STAT_CUN] - 2
self:onStatChange(self.STAT_CUN, -2)
end,
info = function(self, t)
return ([[A life of the mind has had predictably good effects on your Willpower and Cunning.
Increases Willpower and Cunning by %d.]]):format(2*self:getTalentLevelRaw(t))
end,
}
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyEncodePage.lua | 1 | 9847 | --[[
Title: WorldKeyEncodePage
Author(s): yangguiyi
Date: 2021/4/28
Desc:
Use Lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyEncodePage.lua").Show();
--]]
local WorldKeyEncodePage = NPL.export();
local KeepworkServiceProject = NPL.load("(gl)Mod/WorldShare/service/KeepworkService/Project.lua")
local WorldKeyManager = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyManager.lua")
local page
WorldKeyEncodePage.DefaultData = {
encode_nums_text = 100,
txt_file_name = "激活码",
}
function WorldKeyEncodePage.OnInit()
page = document:GetPageCtrl();
page.OnClose = WorldKeyEncodePage.CloseView
end
function WorldKeyEncodePage.Show(projectId)
WorldKeyEncodePage.projectId = projectId or GameLogic.options:GetProjectId()
local projectId = WorldKeyEncodePage.projectId
KeepworkServiceProject:GetProject(projectId, function(data, err)
if type(data) == 'table' then
if WorldKeyEncodePage.DefaultData.txt_file_path == nil then
WorldKeyEncodePage.DefaultData.txt_file_path = string.gsub(ParaIO.GetWritablePath().."temp/Key", "/", "\\")
end
WorldKeyEncodePage.world_data = data
WorldKeyEncodePage.ShowView()
end
end)
end
function WorldKeyEncodePage.ShowView()
if page and page:IsVisible() then
return
end
local params = {
url = "script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyEncodePage.html",
name = "WorldKeyEncodePage.Show",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
zorder = 0,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -510/2,
y = -384/2,
width = 510,
height = 384,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
WorldKeyEncodePage.InitView()
end
function WorldKeyEncodePage.FreshView()
local parent = page:GetParentUIObject()
end
function WorldKeyEncodePage.OnRefresh()
if(page)then
page:Refresh(0);
end
WorldKeyEncodePage.FreshView()
end
function WorldKeyEncodePage.CloseView()
WorldKeyEncodePage.ClearData()
end
function WorldKeyEncodePage.ClearData()
end
function WorldKeyEncodePage.InitView()
local params = WorldKeyEncodePage.world_data or {}
local extra = params.extra or {}
local world_encodekey_data = extra.world_encodekey_data or {}
local buy_link_text = world_encodekey_data.buy_link_text
if buy_link_text then
page:SetValue("buy_link_text", buy_link_text)
end
local title_text = world_encodekey_data.title_text or ""
page:SetValue("title_text", title_text)
local projectId = params.id
local encode_world_data = GameLogic.GetPlayerController():LoadRemoteData("WorldKeyEncodePage.encode_world_data" .. projectId) or {};
local encode_nums_text = encode_world_data.encode_nums_text or WorldKeyEncodePage.DefaultData.encode_nums_text
WorldKeyEncodePage.last_encode_nums = encode_nums_text
page:SetValue("encode_nums_text", encode_nums_text)
local txt_file_name = encode_world_data.txt_file_name or WorldKeyEncodePage.DefaultData.txt_file_name
page:SetValue("txt_file_name", txt_file_name)
local txt_file_path = encode_world_data.txt_file_path or WorldKeyEncodePage.DefaultData.txt_file_path
txt_file_path = commonlib.Encoding.DefaultToUtf8(txt_file_path)
page:SetValue("txt_file_path", txt_file_path)
end
function WorldKeyEncodePage.EncodeKey()
if GameLogic.IsReadOnly() then
return
end
if not GameLogic.GetFilters():apply_filters('is_signed_in') then
GameLogic.AddBBS(nil, L"请先登录", 3000, "255 0 0")
return
end
if not GameLogic.IsVip() then
local VipToolNew = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/VipToolTip/VipToolNew.lua")
VipToolNew.Show("worldkey_encode")
return
end
local buy_link_text = page:GetValue("buy_link_text");
if not buy_link_text or buy_link_text == "" then
GameLogic.AddBBS(nil, L"请输入激活码淘宝购买链接", 3000, "255 0 0")
return
end
local title_text = page:GetValue("title_text") or ""
if not title_text or title_text == "" then
GameLogic.AddBBS(nil, L"请输入标题", 3000, "255 0 0")
return
end
local encode_nums_text = page:GetValue("encode_nums_text");
encode_nums_text = tonumber(encode_nums_text)
if not encode_nums_text then
GameLogic.AddBBS(nil, L"请输入生成数量", 3000, "255 0 0")
return
end
if encode_nums_text > 10000 then
GameLogic.AddBBS(nil, L"一次生成数量不能超过10000", 3000, "255 0 0")
return
end
local float_num = encode_nums_text - math.floor(encode_nums_text)
if float_num > 0 then
GameLogic.AddBBS(nil, L"请输入正确数字", 3000, "255 0 0")
return
end
local txt_file_name = page:GetValue("txt_file_name");
if not txt_file_name then
GameLogic.AddBBS(nil, L"请输入生成文件名", 3000, "255 0 0")
return
end
local txt_file_path = page:GetValue("txt_file_path");
if txt_file_path == "" then
GameLogic.AddBBS(nil, L"请输入生成文件的存放路径", 3000, "255 0 0")
return
end
txt_file_path = commonlib.Encoding.Utf8ToDefault(txt_file_path)
if txt_file_path ~= WorldKeyEncodePage.DefaultData.txt_file_path and not ParaIO.DoesFileExist(txt_file_path) then
GameLogic.AddBBS(nil, L"目标文件夹不存在", 3000, "255 0 0")
return
end
local params = {
extra = {
world_encodekey_data = {}
}
}
local params = WorldKeyEncodePage.world_data or {}
local extra = params.extra or {}
params.extra = extra
local world_encodekey_data = params.extra.world_encodekey_data or {}
extra.world_encodekey_data = world_encodekey_data
world_encodekey_data.buy_link_text = buy_link_text
world_encodekey_data.title_text = title_text
-- world_encodekey_data.encode_nums_text = encode_nums_text
-- world_encodekey_data.txt_file_name = txt_file_name
-- world_encodekey_data.txt_file_path = txt_file_path
local projectId = WorldKeyEncodePage.projectId
KeepworkServiceProject:UpdateProject(projectId, params, function(data, err)
if err == 200 then
local data = {}
data.encode_nums_text = encode_nums_text
data.txt_file_name = txt_file_name
data.txt_file_path = txt_file_path
GameLogic.GetPlayerController():SaveRemoteData("WorldKeyEncodePage.encode_world_data" .. projectId, data);
WorldKeyManager.GenerateActivationCodes(encode_nums_text, System.User.username, projectId, txt_file_name, txt_file_path, function(path)
-- local desc = string.format("激活码生成成功,是否打开%s.txt文件", txt_file_name)
local desc = "激活码生成成功,是否打开生成文件夹"
_guihelper.MessageBox(desc, function(res)
if(res == _guihelper.DialogResult.OK) then
ParaGlobal.ShellExecute("open", "explorer.exe", txt_file_path, "", 1)
end
end, _guihelper.MessageBoxButtons.OKCancel_CustomLabel,nil,nil,nil,nil,{ ok = L"是", cancel = L"否", title = L"生成激活码", });
end)
-- GameLogic.AddBBS(nil, L"设置成功", 3000, "0 255 0")
end
end)
end
function WorldKeyEncodePage.SelectFilePath()
-- local txt_file_path = page:GetValue("txt_file_path");
NPL.load("(gl)script/ide/OpenFileDialog.lua");
local filename = CommonCtrl.OpenFileDialog.ShowOpenFolder_Win32()
print("daaaaaaaaaaa", filename, filename ~= WorldKeyEncodePage.DefaultData.txt_file_path and not ParaIO.DoesFileExist(filename))
if filename ~= WorldKeyEncodePage.DefaultData.txt_file_path and not ParaIO.DoesFileExist(filename) then
filename = WorldKeyEncodePage.DefaultData.txt_file_path
end
filename = commonlib.Encoding.DefaultToUtf8(filename)
page:SetValue("txt_file_path", filename)
end
function WorldKeyEncodePage.OpenFilePath()
local txt_file_path = page:GetValue("txt_file_path");
txt_file_path = commonlib.Encoding.Utf8ToDefault(txt_file_path)
if txt_file_path == "" or not ParaIO.DoesFileExist(txt_file_path) then
return
end
ParaGlobal.ShellExecute("open", "explorer.exe", txt_file_path, "", 1)
end
function WorldKeyEncodePage.WriteOut()
local InvalidKeyPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/InvalidKeyPage.lua");
InvalidKeyPage.Show(WorldKeyEncodePage.world_data);
end
function WorldKeyEncodePage.OnEncodeNumChange()
local encode_nums_text = page:GetValue("encode_nums_text");
if encode_nums_text == "" then
return
end
local encode_nums_text = tonumber(encode_nums_text)
local last_num = WorldKeyEncodePage.last_encode_nums or WorldKeyEncodePage.DefaultData.encode_nums_text
if not encode_nums_text then
page:SetValue("encode_nums_text", last_num);
local root = ParaUI.GetUIObject("ui_encode_nums_text");
root:LostFocus()
return
end
local float_num = encode_nums_text - math.floor(encode_nums_text)
if float_num > 0 then
page:SetValue("encode_nums_text", last_num);
local root = ParaUI.GetUIObject("ui_encode_nums_text");
root:LostFocus()
return
end
WorldKeyEncodePage.last_encode_nums = encode_nums_text
end | gpl-2.0 |
tempbottle/openlua | src/testlist.lua | 2 | 4087 | --[[----------------------------------------------
Õë¶Ôlist.luaµÄ²âÊÔ´úÂë
--]]----------------------------------------------
dofile("list.lua")
local empty = List{}
assert(empty:Count() == 0)
local number1 = List{1979}
assert(number1:Count() == 1)
assert(number1:Get(1) == 1979)
local string1 = List{"djf"}
assert(string1:Count() == 1)
assert(string1:Get(1) == "djf")
local bool2 = List{true,false}
assert(bool2:Count() == 2)
assert(bool2:Get(1) == true)
assert(bool2:Get(2) == false)
local list2 = List{1,1,1979,1979,"soloist","soloist"}
assert(list2:Count() == 6)
assert(list2:Get(3) == list2:Get(4))
assert(list2:Get(4) == 1979)
assert(list2:Get(5) == list2:Get(6))
assert(list2:Get(6) == "soloist")
local list3 = List{List{3,5},List{3,5},"temp",1840}
assert(list3:Count() == 4);
assert(list3:Get(1) == list3:Get(2))
assert(list3:Get(2) == List{3,5});
assert(list3:Last() == 1840)
assert(list3:Find(List{3,5}) == 1)
assert(list3:Find(List{3,5},2) == 2)
assert(list3:Find("temp") == 3)
assert(list3:Sub(3) == List{"temp",1840})
assert(list3:Sub(2,3) == List{List{3,5},"temp"})
local other = List{1979,{4,5},{4,5}}
assert(other:Count() == 3)
-- test relational operations
local function TestLess(list1,list2)
assert(list1 ~= list2)
assert(list2 ~= list1)
assert(list1 <= list2)
assert(list2 >= list1)
assert(list1 < list2)
assert(list2 > list1)
assert(not (list1 >= list2))
assert(not (list1 > list2))
assert(not (list2 <= list1))
assert(not (list2 < list1))
assert(list1:Count() < list2:Count())
end
local function TestLessOrEqual(list1,list2)
assert(list1 <= list2)
assert(list2 >= list1)
assert(not (list1 > list2))
assert(not (list2 < list1))
assert(list1:Count() <= list2:Count())
end
local function TestEqual(list1,list2)
assert(list1 == list2)
assert(list2 == list1)
assert(list1 <= list2)
assert(list1 >= list2)
assert(list2 <= list1)
assert(list2 >= list1)
assert(not (list1 > list2))
assert(not (list1 < list2))
assert(not (list2 > list1))
assert(not (list2 < list1))
assert(list1:Count() == list2:Count())
end
local function TestNotEqual(list1,list2)
assert(list1 ~= list2)
assert(list2 ~= list1)
assert(not (list1 == list2))
assert(not (list2 == list1))
end
TestEqual(empty,List{})
TestEqual(empty,empty)
TestLess(empty,number1)
TestLess(empty,string1)
TestLess(empty,bool2)
TestNotEqual(number1,string1)
TestNotEqual(string1,bool2)
TestNotEqual(number1,bool2)
TestNotEqual(List{3,4,5},List{3,5,4})
local list4 = List{1,"temp","temp",List{3,5},1979}
TestEqual(list4,list4)
local list5 = List{1,"temp","temp",List{3,5}}
TestEqual(list5,list5)
TestLess(list5,list4)
local list6 = List{1,"temp","temp",List{3,5},1979,List{"djf","yaoyao"}}
TestEqual(list6,list6)
TestLess(list4,list6)
TestLess(list5,list6)
local list7 = List{"temp","temp"}
TestNotEqual(list7,list6)
-- test list arithmatic operations
local function TestIdentity(list)
local empty = List{}
TestEqual(list,list..empty)
TestEqual(list,empty..list)
TestEqual(empty,-empty)
TestEqual(list,-(-list))
end
local function TestArith(o1,o2)
local c1 = o1..o2
assert(c1:Count() == o1:Count() + o2:Count())
local c2 = (-o2)..(-o1)
TestEqual(-c1,c2)
end
TestIdentity(empty)
TestIdentity(number1)
TestIdentity(string1);
TestIdentity(bool2)
local a1 = List{56,78,"you"}
local a2 = List{"you",33,"we"}
local a3 = List{56,78,"you","you",33,"we"}
local a4 = List{"we",33,"you","you",78,56}
TestIdentity(a1)
TestIdentity(a2)
TestIdentity(a3)
TestArith(a1,a2)
TestEqual(a1..a2,a3)
TestEqual(-a3,a4)
local b1 = List{List{5,7,9,"temp"},58}
local b2 = List{List{5,7,9},100,"djf"}
local b3 = List{List{5,7,9,"temp"},58,List{5,7,9},100,"djf"}
local b4 = List{List{5,7,9},100,"djf",List{5,7,9,"temp"},58}
TestIdentity(b1)
TestIdentity(b2)
TestEqual(b1..b2,b3)
TestEqual(b2..b1,b4)
assert(b4:Find(List{5,7,9,"temp"}) == 4)
assert(b4:Find(List{5,7,9,"temp"},4) == 4)
assert(b4:Find(List{5,7,9,"temp"},88) == nil)
assert(b4:Find(77) == nil)
for i,e in b3:Traverse() do
assert(e == b3:Get(i))
end | mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Bastok/npcs/Bartolomeo.lua | 1 | 1561 | -----------------------------------
-- Area: Port Bastok
-- NPC: Bartolomeo
-- Standard Info NPC
-- Involved in Quest: Welcome to Bastok
-----------------------------------
require("scripts/globals/keyitems");
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
WelcometoBastok = player:getQuestStatus(BASTOK,WELCOME_TO_BASTOK);
questStatus = player:getVar("WelcometoBastok_Event");
itemEquipped = player:getEquipID(1);
if (WelcometoBastok == 1 and questStatus ~= 1 and itemEquipped == SHELL_SHIELD) then
player:startEvent(0x0034);
else
player:startEvent(0x008c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x34 and WelcometoBastok == 1) then
player:setVar("WelcometoBastok_Event",1)
end
end;
| gpl-3.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/modules/base/luasrc/http/protocol/conditionals.lua | 88 | 4757 | --[[
HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
--- LuCI http protocol implementation - HTTP/1.1 bits.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
--- Implement 14.19 / ETag.
-- @param stat A file.stat structure
-- @return String containing the generated tag suitable for ETag headers
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
--- 14.24 / If-Match
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating whether the precondition is ok
-- @return Alternative status code if the precondition failed
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
--- 14.25 / If-Modified-Since
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating whether the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
--- 14.26 / If-None-Match
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating whether the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
local method = req.env and req.env.REQUEST_METHOD or "GET"
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if method == "GET" or method == "HEAD" then
return false, 304, {
["ETag"] = etag;
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
--- 14.27 / If-Range
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating whether the precondition is ok
-- @return Alternative status code if the precondition failed
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
--- 14.28 / If-Unmodified-Since
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating whether the precondition is ok
-- @return Alternative status code if the precondition failed
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/quests/void-gerlyk.lua | 3 | 1297 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
name = "In the void, no one can hear you scream"
desc = function(self, who)
local desc = {}
desc[#desc+1] = "You have destroyed the sorcerers. Sadly, the portal to the Void remains open; the Creator is coming."
desc[#desc+1] = "This cannot be allowed to happen. After thousands of years trapped in the Void between the stars, Gerlyk is mad with rage."
desc[#desc+1] = "You must now finish what the Sher'tuls started. Take the Staff of Absorption and become a Godslayer yourself."
return table.concat(desc, "\n")
end
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/SchoolCenter/TeacherPage.lua | 1 | 14978 | --[[
Title: TeacherPage
Author(s): yangguiyi
Date: 2021/6/2
Desc:
Use Lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SchoolCenter/TeacherPage.lua").Show();
--]]
local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua");
local HttpWrapper = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/HttpWrapper.lua");
local KeepworkServiceSchoolAndOrg = NPL.load("(gl)Mod/WorldShare/service/KeepworkService/SchoolAndOrg.lua")
local XcodePage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SchoolCenter/XcodePage.lua")
local KeepworkService = NPL.load("(gl)Mod/WorldShare/service/KeepworkService.lua")
local QuestWork = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Quest/QuestWork.lua");
local TeacherPage = NPL.export();
local server_time = 0
local page
function TeacherPage.OnInit()
page = document:GetPageCtrl();
page.OnClose = TeacherPage.CloseView
if TeacherPage.show_callback then
TeacherPage.show_callback(page)
TeacherPage.show_callback = nil
end
TeacherPage.NameToFunction = {
["teaching_management_plaform"] = TeacherPage.OpenTeachingPlanCenter,
["online_plans"] = TeacherPage.OpenOnlinePlans,
["reset_password"] = TeacherPage.OpenResetPassWord,
["teach_statistics"] = TeacherPage.OpenTeachStatistics,
["lesson_progress"] = TeacherPage.OpenLessonProgress,
["work_progress"] = TeacherPage.OpenWorkProgress,
["3d_school"] = TeacherPage.Open3dSchool,
["school_page"] = TeacherPage.OpenSchoolPage,
["3d_school_management"] = TeacherPage.Open3dSchoolManagement,
["class_management"] = TeacherPage.OpenClassManagement,
["students_work"] = TeacherPage.OpenStudentsWork,
["my_work"] = TeacherPage.OpenMyWork,
["history_work"] = TeacherPage.OpenHistoryWork,
["my_project"] = TeacherPage.OpenMyProject,
["personal_data_statistics"] = TeacherPage.OpenPersonalDataStatistics,
["comple_rel_name"] = TeacherPage.OpenCompleRelName,
["comple_school_info"] = TeacherPage.OpenCompleSchoolInfo,
["comple_class_info"] = TeacherPage.OpenCompleClassInfo,
}
end
function TeacherPage.Show(shcool_id)
TeacherPage.shcool_id = shcool_id
TeacherPage.ShowView()
end
function TeacherPage.ClosePage()
page:CloseWindow(0)
TeacherPage.CloseView()
end
function TeacherPage.ShowView()
if page and page:IsVisible() then
return
end
TeacherPage.HandleData()
local params = {
url = "script/apps/Aries/Creator/Game/Tasks/SchoolCenter/TeacherPage.html",
name = "TeacherPage.Show",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
zorder = 0,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -1062/2,
y = -614/2,
width = 1062,
height = 614,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function TeacherPage.FreshView()
local parent = page:GetParentUIObject()
end
function TeacherPage.OnRefresh()
if(page)then
page:Refresh(0);
end
TeacherPage.FreshView()
end
function TeacherPage.CloseView()
TeacherPage.ClearData()
end
function TeacherPage.ClearData()
end
function TeacherPage.HandleData()
end
function TeacherPage.ClickBt(name)
if TeacherPage.NameToFunction[name] then
TeacherPage.NameToFunction[name]()
end
end
function TeacherPage.OpenTeachingPlanCenter()
if TeacherPage.shcool_id == nil then
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
return
end
KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
for key, item in ipairs(orgData) do
if item.schoolId == TeacherPage.shcool_id then
local userType = Mod.WorldShare.Store:Get('user/userType')
if not userType or type(userType) ~= 'table' then
break
end
local orgUrl = item.orgUrl
-- if userType.orgAdmin then
-- local url = '/org/' .. orgUrl .. '/admin/packages'
-- Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- end
-- if userType.teacher then
-- end
local url = '/org/' .. orgUrl .. '/teacher/teach/'
Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- if userType.student or userType.freeStudent then
-- local url = '/org/' .. orgUrl .. '/student'
-- Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- end
return
end
end
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
end)
end
function TeacherPage.OpenOnlinePlans()
GameLogic.AddBBS(nil, L"敬请期待", 3000, "255 0 0")
end
function TeacherPage.OpenResetPassWord()
if TeacherPage.shcool_id == nil then
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
return
end
KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
for key, item in ipairs(orgData) do
if item.schoolId == TeacherPage.shcool_id then
-- local userType = Mod.WorldShare.Store:Get('user/userType')
-- if not userType or type(userType) ~= 'table' then
-- break
-- end
local orgUrl = item.orgUrl
local url = '/org/' .. orgUrl .. '/admin/classes/student'
Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
return
end
end
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
end)
end
function TeacherPage.OpenTeachStatistics()
XcodePage.Show("teach_statistics")
end
function TeacherPage.OpenLessonProgress()
XcodePage.Show("lesson_progress")
end
function TeacherPage.OpenWorkProgress()
XcodePage.Show("work_progress")
end
function TeacherPage.Open3dSchool()
if TeacherPage.shcool_id == nil then
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
return
end
KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
for key, item in ipairs(orgData) do
if item.schoolId == TeacherPage.shcool_id then
if item and item.paraWorld and item.paraWorld.projectId then
local currentEnterWorld = Mod.WorldShare.Store:Get('world/currentEnterWorld')
TeacherPage.ClosePage()
if currentEnterWorld and currentEnterWorld.text then
_guihelper.MessageBox(
format(L"即将离开【%s】进入【%s】", currentEnterWorld.text, item.paraWorld.name),
function(res)
if res and res == _guihelper.DialogResult.Yes then
GameLogic.RunCommand("/loadworld -auto " .. item.paraWorld.projectId)
end
end,
_guihelper.MessageBoxButtons.YesNo
)
else
GameLogic.RunCommand("/loadworld -auto " .. item.paraWorld.projectId)
end
return
end
GameLogic.AddBBS(nil, L"学校暂无3d校园", 3000, "255 0 0")
return
end
end
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
end)
end
function TeacherPage.OpenSchoolPage()
if TeacherPage.shcool_id == nil then
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
return
end
KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
for key, item in ipairs(orgData) do
if item.schoolId == TeacherPage.shcool_id then
local orgUrl = item.orgUrl or ""
local url = KeepworkService:GetKeepworkUrl() .. "/org/" .. orgUrl .. "/index"
ParaGlobal.ShellExecute("open", url, "", "", 1)
return
end
end
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
end)
end
function TeacherPage.Open3dSchoolManagement()
XcodePage.Show("3d_school_management")
end
function TeacherPage.OpenClassManagement()
if TeacherPage.shcool_id == nil then
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
return
end
KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
for key, item in ipairs(orgData) do
if item.schoolId == TeacherPage.shcool_id then
-- local userType = Mod.WorldShare.Store:Get('user/userType')
-- if not userType or type(userType) ~= 'table' then
-- break
-- end
local orgUrl = item.orgUrl
-- if userType.orgAdmin then
-- local url = '/org/' .. orgUrl .. '/admin/packages'
-- Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- end
local url = '/org/' .. orgUrl .. '/teacher/teach/'
Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- if userType.student or userType.freeStudent then
-- local url = '/org/' .. orgUrl .. '/student'
-- Mod.WorldShare.Utils.OpenKeepworkUrlByToken(url)
-- end
return
end
end
GameLogic.AddBBS(nil, L"请先加入学校", 3000, "255 0 0")
end)
end
function TeacherPage.OpenStudentsWork()
-- KeepworkServiceSchoolAndOrg:GetUserAllOrgs(function(orgData)
-- print("ccccccccccccc")
-- echo(orgData, true)
-- end)
-- KeepworkServiceSchoolAndOrg:GetUserAllSchools(function(data, err)
-- print("aaaaaaaaaaaaaaaaaa")
-- echo(data, true)
-- if not data or not data.id then
-- return
-- end
-- KeepworkServiceSchoolAndOrg:GetMyClassList(data.id, function(data, err)
-- print("bbbbbbbbbbbbbbbbbb")
-- echo(data, true)
-- if data and type(data) == 'table' then
-- -- for key, item in ipairs(data) do
-- -- self.classList[#self.classList + 1] = {
-- -- id = item.id,
-- -- name = item.name
-- -- }
-- -- end
-- -- MainPagePage:GetNode('class_list'):SetUIAttribute("DataSource", self.classList)
-- end
-- end)
-- end)
GameLogic.GetFilters():apply_filters('show_offical_worlds_page')
TeacherPage.ClosePage()
end
function TeacherPage.OpenMyWork()
local status = 0
keepwork.quest_work_list.get({
status = status, -- 0,未完成;1已完成
},function(err, msg, data)
-- print("dddddddddddddddd")
-- echo(data, true)
if err == 200 then
if data.rows and #data.rows == 0 then
GameLogic.AddBBS(nil, L"暂无练习", 3000, "255 0 0")
return
end
QuestWork.Show(1)
end
end)
end
function TeacherPage.OpenHistoryWork()
local status = 1
keepwork.quest_work_list.get({
status = status, -- 0,未完成;1已完成
},function(err, msg, data)
-- print("dddddddddddddddd")
-- echo(data, true)
if err == 200 then
if data.rows and #data.rows == 0 then
GameLogic.AddBBS(nil, L"暂无历史成绩", 3000, "255 0 0")
return
end
QuestWork.Show(2)
end
end)
end
function TeacherPage.OpenMyProject()
-- local page = NPL.load("Mod/GeneralGameServerMod/App/ui/page.lua");
-- last_page_ctrl = page.ShowUserInfoPage({HeaderTabIndex="works"});
local Page = NPL.load("Mod/GeneralGameServerMod/UI/Page.lua");
Page.ShowUserInfoPage({HeaderTabIndex="works"});
end
function TeacherPage.OpenPersonalDataStatistics()
XcodePage.Show("personal_data_statistics")
end
function TeacherPage.OpenCompleRelName()
GameLogic.GetFilters():apply_filters(
'show_certificate',
function(result)
if (result) then
if page then
page:Refresh(0.01)
end
end
end
);
end
function TeacherPage.OpenCompleSchoolInfo()
local MySchool = NPL.load("(gl)Mod/WorldShare/cellar/MySchool/MySchool.lua")
MySchool:ShowJoinSchool(function()
KeepWorkItemManager.LoadProfile(false, function()
local profile = KeepWorkItemManager.GetProfile()
if profile and profile.schoolId and profile.schoolId > 0 then
TeacherPage.shcool_id = profile.schoolId
page:Refresh(0.01)
end
end)
end)
end
function TeacherPage.OpenCompleClassInfo()
local profile = KeepWorkItemManager.GetProfile()
if not profile or not profile.schoolId or profile.schoolId == 0 then
GameLogic.AddBBS(nil, L"请先选择学校", 3000, "255 0 0")
return
end
local Page = NPL.load("Mod/GeneralGameServerMod/UI/Page.lua");
Page.Show({OnFinish = function()
GameLogic.AddBBS(nil, L"加入班级成功", 3000, "0 255 0")
page:Refresh(0.01)
end}, {url = "%vue%/Page/User/EditClass.html"});
-- ShowWindow({
-- OnFinish = function(className)
-- -- self.className = className or "";
-- -- self.isPrefectUserInfo = Keepwork:IsPrefectUserInfo();
-- end
-- }, {
-- url = "%vue%/Page/User/EditClass.html",
-- draggable = false,
-- })
end
function TeacherPage.IsShowReimd()
return TeacherPage.IsShowRealName() or TeacherPage.IsShowSchoolInfo() or TeacherPage.IsShowClassInfo()
end
function TeacherPage.IsShowRealName()
if GameLogic.GetFilters():apply_filters('service.session.is_real_name') then
return false
end
return true
end
function TeacherPage.IsShowSchoolInfo()
local profile = KeepWorkItemManager.GetProfile()
if profile and profile.schoolId and profile.schoolId > 0 then
return false
end
return true
end
function TeacherPage.IsShowClassInfo()
local profile = KeepWorkItemManager.GetProfile()
if profile and profile.school and profile.school.type == "大学" then
return false
end
if profile and profile.class ~= nil then
return false
end
return true
end | gpl-2.0 |
madpilot78/ntopng | scripts/lua/modules/check_templates/long_lived.lua | 1 | 1697 | --
-- (C) 2019-21 - ntop.org
--
-- ##############################################
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/check_templates/?.lua;" .. package.path
-- Import the classes library.
local classes = require "classes"
-- Make sure to import the Superclass!
local check_template = require "check_template"
local http_lint = require "http_lint"
-- ##############################################
local long_lived = classes.class(check_template)
-- ##############################################
long_lived.meta = {
}
-- ##############################################
-- @brief Prepare an instance of the template
-- @return A table with the template built
function long_lived:init(check)
-- Call the parent constructor
self.super:init(check)
end
-- #######################################################
function long_lived:parseConfig(conf)
if(tonumber(conf.min_duration) == nil) then
return false, "bad min_duration value"
end
return http_lint.validateListItems(self._check, conf)
end
-- #######################################################
function long_lived:describeConfig(hooks_conf)
if not hooks_conf.all then
return '' -- disabled, nothing to show
end
local conf = hooks_conf.all.script_conf
local msg = i18n("checks.long_lived_flows_descr", {
duration = secondsToTime(conf.min_duration),
})
if(not table.empty(conf.items)) then
msg = msg .. ". " .. i18n("checks.exceptions", {exceptions = table.concat(conf.items, ', ')})
end
return(msg)
end
-- #######################################################
return long_lived
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Xarcabard/npcs/qm1.lua | 1 | 1390 | -----------------------------------
-- Area: Xarcabard
-- NPC: ???
-- Involved in Quests: The Three Magi
-- @zone 112
-- @pos -331 -29 -49
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Xarcabard/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(WINDURST,THE_THREE_MAGI) == QUEST_ACCEPTED and player:hasItem(1104) == false) then
if(trade:hasItemQty(613,1) and trade:getItemCount() == 1) then -- Trade Faded Crystal
player:tradeComplete();
SpawnMob(17236201,180):updateEnmity(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_ORDINARY_HERE);
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 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/bowl_of_wild_stew.lua | 1 | 1668 | -----------------------------------------
-- ID: 4589
-- Item: Bowl of Wild Stew
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 4
-- Agility 1
-- Vitality 2
-- Intelligence -2
-- Attack % 25
-- Attack Cap 50
-- Ranged ATT % 25
-- Ranged ATT Cap 50
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,0,4589);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 50);
target:addMod(MOD_FOOD_RATTP, 25);
target:addMod(MOD_FOOD_RATT_CAP, 50);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 50);
target:delMod(MOD_FOOD_RATTP, 25);
target:delMod(MOD_FOOD_RATT_CAP, 50);
end;
| gpl-3.0 |
RyMarq/Zero-K | gamedata/modularcomms/weapons/torpedo.lua | 1 | 1467 | local name = "commweapon_torpedo"
local weaponDef = {
name = [[Torpedo Launcher]],
areaOfEffect = 16,
avoidFriendly = false,
bouncerebound = 0.5,
bounceslip = 0.5,
burnblow = true,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customParams = {
is_unit_weapon = 1,
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]],
slot = [[5]],
reaim_time = 1,
},
damage = {
default = 220,
subs = 220,
},
explosionGenerator = [[custom:TORPEDO_HIT]],
flightTime = 6,
groundbounce = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
model = [[wep_t_longbolt.s3o]],
numbounce = 4,
noSelfDamage = true,
range = 330,
reloadtime = 3.5,
soundHit = [[explosion/wet/ex_underwater]],
soundStart = [[weapon/torpedo]],
startVelocity = 90,
tracks = true,
turnRate = 10000,
turret = true,
waterWeapon = true,
weaponAcceleration = 25,
weaponType = [[TorpedoLauncher]],
weaponVelocity = 140,
}
return name, weaponDef
| gpl-2.0 |
eXhausted/Ovale | HonorAmongThieves.lua | 1 | 3581 | --[[--------------------------------------------------------------------
Copyright (C) 2014, 2015 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]-------------------------------------------------------------------
--[[
This addon tracks the hidden cooldown of Honor Among Thieves on a
subtlety rogue.
Honor Among Thieves description from wowhead.com:
Critical hits in combat by you or by your party or raid members grant
you a combo point, but no more often than once every 2 seconds.
Mechanically, there is a hidden buff applied to the player that lasts 2
seconds and prevents critical hits from generating an extra combo point.
--]]
local OVALE, Ovale = ...
local OvaleHonorAmongThieves = Ovale:NewModule("OvaleHonorAmongThieves", "AceEvent-3.0")
Ovale.OvaleHonorAmongThieves = OvaleHonorAmongThieves
--<private-static-properties>
-- Forward declarations for module dependencies.
local OvaleAura = nil
local OvaleData = nil
local API_GetTime = GetTime
local INFINITY = math.huge
-- Player's GUID.
local self_playerGUID = nil
-- Honor Among Thieves spell ID.
local HONOR_AMONG_THIEVES = 51699
-- Use a mean time between procs of 2.2 seconds (estimation from SimulationCraft).
local MEAN_TIME_TO_HAT = 2.2
--</private-static-properties>
--<public-static-properties>
OvaleHonorAmongThieves.spellName = "Honor Among Thieves Cooldown"
-- Honor Among Thieves spell ID from spellbook; re-used as the aura ID of the hidden buff.
OvaleHonorAmongThieves.spellId = HONOR_AMONG_THIEVES
OvaleHonorAmongThieves.start = 0
OvaleHonorAmongThieves.ending = 0
OvaleHonorAmongThieves.duration = MEAN_TIME_TO_HAT
OvaleHonorAmongThieves.stacks = 0
--</public-static-properties>
--<public-static-methods>
function OvaleHonorAmongThieves:OnInitialize()
-- Resolve module dependencies.
OvaleAura = Ovale.OvaleAura
OvaleData = Ovale.OvaleData
end
function OvaleHonorAmongThieves:OnEnable()
if Ovale.playerClass == "ROGUE" then
self_playerGUID = Ovale.playerGUID
self:RegisterMessage("Ovale_SpecializationChanged")
end
end
function OvaleHonorAmongThieves:OnDisable()
if Ovale.playerClass == "ROGUE" then
self:UnregisterMessage("Ovale_SpecializationChanged")
end
end
function OvaleHonorAmongThieves:Ovale_SpecializationChanged(event, specialization, previousSpecialization)
if specialization == "subtlety" then
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
else
self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
end
function OvaleHonorAmongThieves:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...)
local arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25 = ...
if sourceGUID == self_playerGUID and destGUID == self_playerGUID and cleuEvent == "SPELL_ENERGIZE" then
local spellId, powerType = arg12, arg16
if spellId == HONOR_AMONG_THIEVES and powerType == 4 then
local now = API_GetTime()
self.start = now
-- Prefer the duration set in the script, if given; otherwise, default to MEAN_TIME_TO_HAT.
local duration = OvaleData:GetSpellInfoProperty(HONOR_AMONG_THIEVES, now, "duration", destGUID) or MEAN_TIME_TO_HAT
self.duration = duration
self.ending = self.start + duration
self.stacks = 1
OvaleAura:GainedAuraOnGUID(self_playerGUID, self.start, self.spellId, self_playerGUID, "HELPFUL", nil, nil, self.stacks, nil, self.duration, self.ending, nil, self.spellName, nil, nil, nil)
end
end
end
--</public-static-methods>
| mit |
SammyJames/LootDrop | Libs/LibAddonMenu-2.0/LibAddonMenu-2.0.lua | 2 | 11309 | -- LibAddonMenu-2.0 & its files © Ryan Lakanen (Seerah) --
-- All Rights Reserved --
-- Permission is granted to use Seerah's LibAddonMenu-2.0 --
-- in your project. Any modifications to LibAddonMenu-2.0 --
-- may not be redistributed. --
--------------------------------------------------------------
--Register LAM with LibStub
local MAJOR, MINOR = "LibAddonMenu-2.0", 16
local lam, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not lam then return end --the same or newer version of this lib is already loaded into memory
--UPVALUES--
local wm = WINDOW_MANAGER
local cm = CALLBACK_MANAGER
local tinsert = table.insert
local optionsWindow = ZO_OptionsWindowSettingsScrollChild
local _
local addonsForList = {}
local addonToOptionsMap = {}
local optionsCreated = {}
lam.widgets = lam.widgets or {}
local widgets = lam.widgets
--METHOD: REGISTER WIDGET--
--each widget has its version checked before loading,
--so we only have the most recent one in memory
--Usage:
-- widgetType = "string"; the type of widget being registered
-- widgetVersion = integer; the widget's version number
LAMCreateControl = LAMCreateControl or {}
local lamcc = LAMCreateControl
function lam:RegisterWidget(widgetType, widgetVersion)
if widgets[widgetType] and widgets[widgetType] >= widgetVersion then
return false
else
widgets[widgetType] = widgetVersion
return true
end
end
--METHOD: OPEN TO ADDON PANEL--
--opens to a specific addon's option panel
--Usage:
-- panel = userdata; the panel returned by the :RegisterOptionsPanel method
--local settings = {en = "Settings", de = "Einstellungen", fr = "Réglages"}
--local locSettings = settings[GetCVar("Language.2")]
local locSettings = GetString(SI_GAME_MENU_SETTINGS)
function lam:OpenToPanel(panel)
SCENE_MANAGER:Show("gameMenuInGame")
zo_callLater(function()
ZO_GameMenu_InGame.gameMenu.headerControls[locSettings]:SetOpen(true)
SCENE_MANAGER:AddFragment(OPTIONS_WINDOW_FRAGMENT)
--ZO_OptionsWindow_ChangePanels(lam.panelID)
KEYBOARD_OPTIONS:ChangePanels(lam.panelID)
--if not lam.panelSubCategoryControl then
-- lam.panelSubCategoryControl = _G["ZO_GameMenu_InGameNavigationContainerScrollChildZO_GameMenu_SubCategory"..(lam.panelID + 1)]
--end
--ZO_TreeEntry_OnMouseUp(lam.panelSubCategoryControl, true)
panel:SetHidden(false)
end, 200)
end
--INTERNAL FUNCTION
--creates controls when options panel is first shown
--controls anchoring of these controls in the panel
local function CreateOptionsControls(panel)
local addonID = panel:GetName()
local optionsTable = addonToOptionsMap[addonID]
if optionsTable then
local lastAddedControl, lacAtHalfRow
for _, widgetData in ipairs(optionsTable) do
local widgetType = widgetData.type
if widgetType == "submenu" then
local submenu = LAMCreateControl[widgetType](panel, widgetData)
if lastAddedControl then
submenu:SetAnchor(TOPLEFT, lastAddedControl, BOTTOMLEFT, 0, 15)
else
submenu:SetAnchor(TOPLEFT)
end
lastAddedControl = submenu
lacAtHalfRow = false
local lastAddedControlSub, lacAtHalfRowSub
for _, subWidgetData in ipairs(widgetData.controls) do
local subWidgetType = subWidgetData.type
local subWidget = LAMCreateControl[subWidgetType](submenu, subWidgetData)
local isHalf = subWidgetData.width == "half"
if lastAddedControlSub then
if lacAtHalfRowSub and isHalf then
subWidget:SetAnchor(TOPLEFT, lastAddedControlSub, TOPRIGHT, 5, 0)
lacAtHalfRowSub = false
else
subWidget:SetAnchor(TOPLEFT, lastAddedControlSub, BOTTOMLEFT, 0, 15)
lacAtHalfRowSub = isHalf and true or false
lastAddedControlSub = subWidget
end
else
subWidget:SetAnchor(TOPLEFT)
lacAtHalfRowSub = isHalf and true or false
lastAddedControlSub = subWidget
end
end
else
local widget = LAMCreateControl[widgetType](panel, widgetData)
local isHalf = widgetData.width == "half"
if lastAddedControl then
if lacAtHalfRow and isHalf then
widget:SetAnchor(TOPLEFT, lastAddedControl, TOPRIGHT, 10, 0)
lacAtHalfRow = false
else
widget:SetAnchor(TOPLEFT, lastAddedControl, BOTTOMLEFT, 0, 15)
lacAtHalfRow = isHalf and true or false
lastAddedControl = widget
end
else
widget:SetAnchor(TOPLEFT)
lacAtHalfRow = isHalf and true or false
lastAddedControl = widget
end
end
end
end
optionsCreated[addonID] = true
cm:FireCallbacks("LAM-PanelControlsCreated", panel)
end
--INTERNAL FUNCTION
--handles switching between panels
local function ToggleAddonPanels(panel) --called in OnShow of newly shown panel
local currentlySelected = LAMAddonPanelsMenu.currentlySelected
if currentlySelected and currentlySelected ~= panel then
currentlySelected:SetHidden(true)
end
LAMAddonPanelsMenu.currentlySelected = panel
if not optionsCreated[panel:GetName()] then --if this is the first time opening this panel, create these options
CreateOptionsControls(panel)
end
cm:FireCallbacks("LAM-RefreshPanel", panel)
end
--METHOD: REGISTER ADDON PANEL
--registers your addon with LibAddonMenu and creates a panel
--Usage:
-- addonID = "string"; unique ID which will be the global name of your panel
-- panelData = table; data object for your panel - see controls\panel.lua
function lam:RegisterAddonPanel(addonID, panelData)
local panel = lamcc.panel(nil, panelData, addonID) --addonID==global name of panel
panel:SetHidden(true)
panel:SetAnchor(TOPLEFT, LAMAddonPanelsMenu, TOPRIGHT, 10, 0)
panel:SetAnchor(BOTTOMLEFT, LAMAddonPanelsMenu, BOTTOMRIGHT, 10, 0)
panel:SetWidth(549)
panel:SetDrawLayer(DL_OVERLAY)
tinsert(addonsForList, {panel = addonID, name = panelData.name})
panel:SetHandler("OnShow", ToggleAddonPanels)
if panelData.slashCommand then
SLASH_COMMANDS[panelData.slashCommand] = function()
lam:OpenToPanel(panel)
end
end
return panel --return for authors creating options manually
end
--METHOD: REGISTER OPTION CONTROLS
--registers the options you want shown for your addon
--these are stored in a table where each key-value pair is the order
--of the options in the panel and the data for that control, respectively
--see exampleoptions.lua for an example
--see controls\<widget>.lua for each widget type
--Usage:
-- addonID = "string"; the same string passed to :RegisterAddonPanel
-- optionsTable = table; the table containing all of the options controls and their data
function lam:RegisterOptionControls(addonID, optionsTable) --optionsTable = {sliderData, buttonData, etc}
addonToOptionsMap[addonID] = optionsTable
end
--INTERNAL FUNCTION
--handles switching between LAM's Addon Settings panel and other panels in the Settings menu
local oldDefaultButton = ZO_OptionsWindowResetToDefaultButton
local oldCallback = oldDefaultButton.callback
local dummyFunc = function() end
local panelWindow = ZO_OptionsWindow
local bgL = ZO_OptionsWindowBGLeft
local bgR = ZO_OptionsWindowBGLeftBGRight
local function HandlePanelSwitching(self, panel)
if panel == lam.panelID then --our addon settings panel
oldDefaultButton:SetCallback(dummyFunc)
oldDefaultButton:SetHidden(true)
oldDefaultButton:SetAlpha(0) --just because it still bugs out
panelWindow:SetDimensions(999, 960)
bgL:SetWidth(666)
bgR:SetWidth(333)
else
local shown = LAMAddonPanelsMenu.currentlySelected
if shown then shown:SetHidden(true) end
oldDefaultButton:SetCallback(oldCallback)
oldDefaultButton:SetHidden(false)
oldDefaultButton:SetAlpha(1)
panelWindow:SetDimensions(768, 914)
bgL:SetWidth(512)
bgR:SetWidth(256)
end
end
--INTERNAL FUNCTION
--creates LAM's Addon Settings panel
local function CreateAddonSettingsPanel()
if not LAMSettingsPanelCreated then
local controlPanelID = "LAM_ADDON_SETTINGS_PANEL"
--Russian for TERAB1T's RuESO addon, which creates an "ru" locale
--game font does not support Cyrillic, so they are using custom fonts + extended latin charset
--Spanish provided by Luisen75 for their translation project
local controlPanelNames = {
en = "Addon Settings",
fr = "Extensions",
de = "Erweiterungen",
ru = "Îacòpoéêè äoïoìîeîèé",
es = "Configura Addons",
}
ZO_OptionsWindow_AddUserPanel(controlPanelID, controlPanelNames[GetCVar("Language.2")] or controlPanelName["en"])
lam.panelID = _G[controlPanelID]
--ZO_PreHook("ZO_OptionsWindow_ChangePanels", HandlePanelSwitching)
ZO_PreHook(ZO_SharedOptions, "ChangePanels", HandlePanelSwitching)
LAMSettingsPanelCreated = true
end
end
--INTERNAL FUNCTION
--adds each registered addon to the menu in LAM's panel
local function CreateAddonButtons(list, addons)
for i = 1, #addons do
local button = wm:CreateControlFromVirtual("LAMAddonMenuButton"..i, list.scrollChild, "ZO_DefaultTextButton")
button.name = addons[i].name
button.panel = _G[addons[i].panel]
button:SetText(button.name)
button:SetHorizontalAlignment(TEXT_ALIGN_LEFT)
button:SetWidth(190)
if i == 1 then
button:SetAnchor(TOPLEFT, list.scrollChild, TOPLEFT, 5, 5)
else
button:SetAnchor(TOPLEFT, _G["LAMAddonMenuButton"..i-1], BOTTOMLEFT)
end
button:SetHandler("OnClicked", function(self) self.panel:SetHidden(false) end)
end
end
--INTERNAL FUNCTION
--creates the left-hand menu in LAM's panel
local function CreateAddonList()
local list
--check if an earlier loaded copy of LAM created it already
list = LAMAddonPanelsMenu or wm:CreateControlFromVirtual("LAMAddonPanelsMenu", optionsWindow, "ZO_ScrollContainer")
list:ClearAnchors()
list:SetAnchor(TOPLEFT)
list:SetHeight(675)
list:SetWidth(200)
list.bg = list.bg or wm:CreateControl(nil, list, CT_BACKDROP)
local bg = list.bg
bg:SetAnchorFill() --offsets of 8?
bg:SetEdgeTexture("EsoUI\\Art\\miscellaneous\\borderedinsettransparent_edgefile.dds", 128, 16)
bg:SetCenterColor(0, 0, 0, 0)
list.scrollChild = LAMAddonPanelsMenuScrollChild
list.scrollChild:SetResizeToFitPadding(0, 15)
local generatedButtons
list:SetHandler("OnShow", function(self)
if not generatedButtons and #addonsForList > 0 then
--we're about to show our list for the first time - let's sort the buttons before creating them
table.sort(addonsForList, function(a, b)
return a.name < b.name
end)
CreateAddonButtons(list, addonsForList)
self.currentlySelected = LAMAddonMenuButton1 and LAMAddonMenuButton1.panel
--since our addon panels don't have a parent, let's make sure they hide when we're done with them
ZO_PreHookHandler(ZO_OptionsWindow, "OnHide", function() self.currentlySelected:SetHidden(true) end)
generatedButtons = true
end
if self.currentlySelected then self.currentlySelected:SetHidden(false) end
end)
--list.controlType = OPTIONS_CUSTOM
--list.panel = lam.panelID
list.data = {
controlType = OPTIONS_CUSTOM,
panel = lam.panelID,
}
ZO_OptionsWindow_InitializeControl(list)
return list
end
--INITIALIZING
CreateAddonSettingsPanel()
CreateAddonList()
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Northern_San_dOria/npcs/Abioleget.lua | 1 | 1084 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abioleget
-- Type: Quest Giver (Her Memories: The Faux Pas and The Vicasque's Sermon) / Merchant
-- @zone: 231
-- @pos: 128.771 0.000 118.538
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ABIOLEGET_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
eXhausted/Ovale | DataBroker.lua | 1 | 5108 | --[[--------------------------------------------------------------------
Copyright (C) 2014, 2015 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
local OVALE, Ovale = ...
local OvaleDataBroker = Ovale:NewModule("OvaleDataBroker", "AceEvent-3.0")
Ovale.OvaleDataBroker = OvaleDataBroker
--<private-static-properties>
local L = Ovale.L
local LibDataBroker = LibStub("LibDataBroker-1.1", true)
local LibDBIcon = LibStub("LibDBIcon-1.0", true)
local OvaleDebug = Ovale.OvaleDebug
local OvaleOptions = Ovale.OvaleOptions
-- Forward declarations for module dependencies.
local OvaleScripts = nil
local OvaleVersion = nil
local pairs = pairs
local tinsert = table.insert
local API_CreateFrame = CreateFrame
local API_EasyMenu = EasyMenu
local API_IsShiftKeyDown = IsShiftKeyDown
-- GLOBALS: UIParent
-- Class icon textures.
local CLASS_ICONS = {
["DEATHKNIGHT"] = "Interface\\Icons\\ClassIcon_DeathKnight",
["DRUID"] = "Interface\\Icons\\ClassIcon_Druid",
["HUNTER"] = "Interface\\Icons\\ClassIcon_Hunter",
["MAGE"] = "Interface\\Icons\\ClassIcon_Mage",
["MONK"] = "Interface\\Icons\\ClassIcon_Monk",
["PALADIN"] = "Interface\\Icons\\ClassIcon_Paladin",
["PRIEST"] = "Interface\\Icons\\ClassIcon_Priest",
["ROGUE"] = "Interface\\Icons\\ClassIcon_Rogue",
["SHAMAN"] = "Interface\\Icons\\ClassIcon_Shaman",
["WARLOCK"] = "Interface\\Icons\\ClassIcon_Warlock",
["WARRIOR"] = "Interface\\Icons\\ClassIcon_Warrior",
}
local self_menuFrame = nil
local self_tooltipTitle = nil
do
local defaultDB = {
-- LibDBIcon-1.0 needs a table to store minimap settings.
minimap = {},
}
local options = {
minimap =
{
order = 25,
type = "toggle",
name = L["Show minimap icon"],
get = function(info)
return not Ovale.db.profile.apparence.minimap.hide
end,
set = function(info, value)
Ovale.db.profile.apparence.minimap.hide = not value
OvaleDataBroker:UpdateIcon()
end
},
}
-- Insert defaults and options into OvaleOptions.
for k, v in pairs(defaultDB) do
OvaleOptions.defaultDB.profile.apparence[k] = v
end
for k, v in pairs(options) do
OvaleOptions.options.args.apparence.args[k] = v
end
OvaleOptions:RegisterOptions(OvaleDataBroker)
end
--</private-static-properties>
--<public-static-properties>
OvaleDataBroker.broker = nil
--</public-static-properties>
--<private-static-methods>
local function OnClick(frame, button)
if button == "LeftButton" then
local menu = {
{ text = L["Script"], isTitle = true },
}
local scriptType = not Ovale.db.profile.showHiddenScripts and "script"
local descriptions = OvaleScripts:GetDescriptions(scriptType)
for name, description in pairs(descriptions) do
local menuItem = {
text = description,
func = function() OvaleScripts:SetScript(name) end,
}
tinsert(menu, menuItem)
end
self_menuFrame = self_menuFrame or API_CreateFrame("Frame", "OvaleDataBroker_MenuFrame", UIParent, "UIDropDownMenuTemplate")
API_EasyMenu(menu, self_menuFrame, "cursor", 0, 0, "MENU")
elseif button == "MiddleButton" then
Ovale:ToggleOptions()
elseif button == "RightButton" then
if API_IsShiftKeyDown() then
OvaleDebug:DoTrace(true)
else
OvaleOptions:ToggleConfig()
end
end
end
local function OnTooltipShow(tooltip)
self_tooltipTitle = self_tooltipTitle or OVALE .. " " .. OvaleVersion.version
tooltip:SetText(self_tooltipTitle, 1, 1, 1)
tooltip:AddLine(L["Click to select the script."])
tooltip:AddLine(L["Middle-Click to toggle the script options panel."])
tooltip:AddLine(L["Right-Click for options."])
tooltip:AddLine(L["Shift-Right-Click for the current trace log."])
end
--</private-static-methods>
--<public-static-methods>
function OvaleDataBroker:OnInitialize()
-- Resolve module dependencies.
OvaleOptions = Ovale.OvaleOptions
OvaleScripts = Ovale.OvaleScripts
OvaleVersion = Ovale.OvaleVersion
-- LDB dataobject
if LibDataBroker then
local broker = {
type = "data source",
text = "",
icon = CLASS_ICONS[Ovale.playerClass],
OnClick = OnClick,
OnTooltipShow = OnTooltipShow,
}
self.broker = LibDataBroker:NewDataObject(OVALE, broker)
if LibDBIcon then
LibDBIcon:Register(OVALE, self.broker, Ovale.db.profile.apparence.minimap)
end
end
end
function OvaleDataBroker:OnEnable()
if self.broker then
self:RegisterMessage("Ovale_ProfileChanged", "UpdateIcon")
self:RegisterMessage("Ovale_ScriptChanged")
self:Ovale_ScriptChanged()
self:UpdateIcon()
end
end
function OvaleDataBroker:OnDisable()
if self.broker then
self:UnregisterMessage("Ovale_ProfileChanged")
self:UnregisterMessage("Ovale_ScriptChanged")
end
end
function OvaleDataBroker:UpdateIcon()
if LibDBIcon and self.broker then
local minimap = Ovale.db.profile.apparence.minimap
LibDBIcon:Refresh(OVALE, minimap)
if minimap.hide then
LibDBIcon:Hide(OVALE)
else
LibDBIcon:Show(OVALE)
end
end
end
function OvaleDataBroker:Ovale_ScriptChanged()
-- Update the LDB dataobject.
self.broker.text = Ovale.db.profile.source
end
--</public-static-methods>
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/intro-thalore.lua | 3 | 1817 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return [[Welcome #LIGHT_GREEN#@name@#WHITE#.
You are of the Thaloren, the Elven race closest to nature. Your people have lived for thousands of years in their forest, rarely taking part in the events of the outside world.
Yet when their home is threatened, the Thaloren Elves can prove to be fearsome combatants.
You lived a peaceful life deep in the forest for many years, but lately you have grown restless and have decided to step into the world.
You have decided to venture into the old and wild places looking for ancient treasures and glory.
You have come to the western side of the Thaloren forest, to the lair of Norgos. Norgos was a steadfast ally of the Thaloren, protecting the western border. But lately he has grown corrupt, even attacking the Thaloren.
To the east of Shatur, the Thaloren Capital, lies a dark part of the woods. Ever since the Spellblaze this area has been corrupted. The wildlife there has been transformed.
After days of travel, you have found Norgos' Lair and entered it. What will you find there...?
]]
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/chats/gates-of-morning-main.lua | 3 | 9921 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newChat{ id="welcome",
text = [[What may I do for you?]],
answers = {
{"Lady Aeryn, at last I am back home! [tell her your story]", jump="return", cond=function(npc, player) return player:hasQuest("start-sunwall") and player:isQuestStatus("start-sunwall", engine.Quest.COMPLETED, "slazish") and not player:isQuestStatus("start-sunwall", engine.Quest.COMPLETED, "return") end, action=function(npc, player) player:setQuestStatus("start-sunwall", engine.Quest.COMPLETED, "return") end},
{"Tell me more about the Gates of Morning.", jump="explain-gates", cond=function(npc, player) return player.faction ~= "sunwall" end},
{"Before I came here, I happened upon members of the Sunwall in Maj'Eyal. Do you know of this?.", jump="sunwall_west", cond=function(npc, player) return game.state.found_sunwall_west and not npc.been_asked_sunwall_west end, action=function(npc, player) npc.been_asked_sunwall_west = true end},
{"I need help in my hunt for clues about the staff.", jump="clues", cond=function(npc, player) return game.state:isAdvanced() and not player:hasQuest("orc-pride") end},
{"I have destroyed the leaders of all the Orc Prides.", jump="prides-dead", cond=function(npc, player) return player:isQuestStatus("orc-pride", engine.Quest.COMPLETED) end},
{"I am back from the Charred Scar, where the orcs took the staff.", jump="charred-scar", cond=function(npc, player) return player:hasQuest("charred-scar") and player:hasQuest("charred-scar"):isCompleted() end},
{"A dying paladin gave me this map; something about orc breeding pits. [tell her the story]", jump="orc-breeding-pits", cond=function(npc, player) return player:hasQuest("orc-breeding-pits") and player:isQuestStatus("orc-breeding-pits", engine.Quest.COMPLETED, "wuss-out") and not player:isQuestStatus("orc-breeding-pits", engine.Quest.COMPLETED, "wuss-out-done") end},
{"Sorry, I have to go!"},
}
}
newChat{ id="return",
text = [[@playername@! We thought you had died in the portal explosion. I am glad we were wrong. You saved the Sunwall.
The news about the staff is troubling. Ah well, please at least take time to rest for a while.]],
answers = {
{"I shall, thank you, my lady.", jump="welcome"},
},
}
newChat{ id="explain-gates",
text = [[There are two main groups in the population here, Humans and Elves.
Humans came here in the Age of Pyre. Our ancestors were part of a Mardrop expedition to find what had happened to the Naloren lands that sunk under the sea. Their ship was wrecked and the survivors landed on this continent.
They came across a group of elves, seemingly native to those lands, and befriended them - founding the Sunwall and the Gates of Morning.
Then the orc pride came and we have been fighting for our survival ever since.]],
answers = {
{"Thank you, my lady.", jump="welcome"},
},
}
newChat{ id="sunwall_west",
text = [[Ahh, so they survived? That is good news...]],
answers = {
{"Go on.", jump="sunwall_west2"},
{"Well, actually...", jump="sunwall_west2", cond=function(npc, player) return game.state.found_sunwall_west_died end},
},
}
newChat{ id="sunwall_west2",
text = [[The people you saw are likely the volunteers of Zemekkys' early experiments regarding the farportals.
He is a mage who resides here in the Sunwall, eccentric but skilled, who believes that creation of a new farportal to Maj'Eyal is possible.
Aside from a few early attempts with questionable results, he hasn't had much luck. Still, it's gladdening to hear that the volunteers for his experiments live, regardless of their location. We are all still under the same Sun, after all.
Actually... maybe it would benefit you if you meet Zemekkys. He would surely be intrigued by that Orb of Many Ways you possess. He lives in a small house just to the north.]],
answers = {
{"Maybe I'll visit him. Thank you.", jump="welcome"},
},
}
newChat{ id="prides-dead",
text = [[The news has indeed reached me. I could scarce believe it, so long have we been at war with the Pride.
Now they are dead? At the hands of just one @playerdescriptor.race@? Truly I am amazed by your power.
While you were busy bringing an end to the orcs, we managed to discover some parts of the truth from a captive orc.
He talked about the shield protecting the High Peak. It seems to be controlled by "orbs of command" which the masters of the Prides had in their possession.
Look for them if you have not yet found them.
He also said the only way to enter the peak and de-activate the shield is through the "slime tunnels", located somewhere in one of the Prides, probably Grushnak.
]],
answers = {
{"Thanks, my lady. I will look for the tunnel and venture inside the Peak.", action=function(npc, player)
player:setQuestStatus("orc-pride", engine.Quest.DONE)
player:grantQuest("high-peak")
end},
},
}
newChat{ id="clues",
text = [[As much as I would like to help, our forces are already spread too thin; we cannot provide you with direct assistance.
But I might be able to help you by explaining how the Pride is organised.
Recently we have heard the Pride speaking about a new master, or masters. They might be the ones behind that mysterious staff of yours.
We believe that the heart of their power is the High Peak, in the center of the continent. But it is inaccessible and covered by some kind of shield.
You must investigate the bastions of the Pride. Perhaps you will find more information about the High Peak, and any orc you kill is one less that will attack us.
The known bastions of the Pride are:
- Rak'shor Pride, in the west of the southern desert
- Gorbat Pride, in a mountain range in the southern desert
- Vor Pride, in the northeast
- Grushnak Pride, on the eastern slope of the High Peak]],
-- - A group of corrupted humans live in Eastport on the southern coastline; they have contact with the Pride
answers = {
{"I will investigate them.", jump="relentless", action=function(npc, player)
player:setQuestStatus("orc-hunt", engine.Quest.DONE)
player:grantQuest("orc-pride")
game.logPlayer(game.player, "Aeryn points to the known locations on your map.")
end},
},
}
newChat{ id="relentless",
text = [[One more bit of aid I might give you before you go. Your tale has moved me, and the very stars shine with approval of your relentless pursuit. Take their blessing, and let nothing stop you in your quest.
#LIGHT_GREEN#*She touches your forehead with one cool hand, and you feel a surge of power*
]],
answers = {
{"I'll leave not a single orc standing.", jump="welcome", action=function(npc, player)
player:learnTalent(player.T_RELENTLESS_PURSUIT, true, 1, {no_unlearn=true})
game.logPlayer(game.player, "#VIOLET#You have learned the talent Relentless Pursuit.")
end},
},
}
newChat{ id="charred-scar",
text = [[I have heard about that; good men lost their lives for this. I hope it was worth it.]],
answers = {
{"Yes, my lady, they delayed the orcs so that I could get to the heart of the volcano. *#LIGHT_GREEN#Tell her what happened#WHITE#*", jump="charred-scar-success",
cond=function(npc, player) return player:isQuestStatus("charred-scar", engine.Quest.COMPLETED, "stopped") end,
},
{"I am afraid I was too late, but I still have some valuable information. *#LIGHT_GREEN#Tell her what happened#WHITE#*", jump="charred-scar-fail",
cond=function(npc, player) return player:isQuestStatus("charred-scar", engine.Quest.COMPLETED, "not-stopped") end,
},
},
}
newChat{ id="charred-scar-success",
text = [[Sorcerers? I have never heard of them. There were rumours about a new master of the Pride, but it seems they have two.
Thank you for everything. You must continue your hunt now that you know what to look for.]],
answers = {
{"I will avenge your men.", action=function(npc, player) player:setQuestStatus("charred-scar", engine.Quest.DONE) end}
},
}
newChat{ id="charred-scar-fail",
text = [[Sorcerers? I have never heard of them. There were rumours about a new master of the Pride, but it seems they have two.
I am afraid with the power they gained today they will be even harder to stop, but we do not have a choice.]],
answers = {
{"I will avenge your men.", action=function(npc, player) player:setQuestStatus("charred-scar", engine.Quest.DONE) end}
},
}
newChat{ id="orc-breeding-pits",
text = [[Ah! This is wonderful! Finally a ray of hope amidst the darkness. I will assign my best troops to this. Thank you, @playername@ - take this as a token of gratitude.]],
answers = {
{"Good luck.", action=function(npc, player)
player:setQuestStatus("orc-breeding-pits", engine.Quest.COMPLETED, "wuss-out-done")
player:setQuestStatus("orc-breeding-pits", engine.Quest.COMPLETED)
for i = 1, 5 do
local ro = game.zone:makeEntity(game.level, "object", {ignore_material_restriction=true, type="gem", special=function(o) return o.material_level and o.material_level >= 5 end}, nil, true)
if ro then
ro:identify(true)
game.logPlayer(player, "Aeryn gives you: %s", ro:getName{do_color=true})
game.zone:addEntity(game.level, ro, "object")
player:addObject(player:getInven("INVEN"), ro)
end
end
end}
},
}
return "welcome"
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/maps/towns/point-zero.lua | 3 | 7321 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
defineTile('<', "RIFT")
defineTile("1", "HARDWALL", nil, nil, "CLOTH_ARMOR_STORE")
defineTile('2', "HARDWALL", nil, nil, "SWORD_WEAPON_STORE")
defineTile('3', "HARDWALL", nil, nil, "KNIFE_WEAPON_STORE")
defineTile('4', "HARDWALL", nil, nil, "ARCHER_WEAPON_STORE")
defineTile('5', "HARDWALL", nil, nil, "STAFF_WEAPON_STORE")
defineTile('6', "HARDWALL", nil, nil, "LIGHT_ARMOR_STORE")
defineTile('7', "HARDWALL", nil, nil, "RUNEMASTER")
defineTile('8', "HARDWALL", nil, nil, "JEWELRY")
defineTile("~", "DEEP_WATER")
defineTile("*", "OUTERSPACE")
defineTile("^", "HARDMOUNTAIN_WALL")
defineTile("-", "FLOATING_ROCKS")
defineTile("t", "TREE")
defineTile("s", "COLD_FOREST")
defineTile(".", "GRASS")
defineTile("=", "SPACETIME_RIFT")
defineTile("_", "VOID")
defineTile("#", "HARDWALL")
defineTile("Z", "VOID", nil, "ZEMEKKYS")
startx = 24
starty = 29
-- addSpot section
addSpot({1, 2}, "pop", "foes")
addSpot({2, 2}, "pop", "foes")
addSpot({1, 3}, "pop", "foes")
addSpot({2, 3}, "pop", "foes")
addSpot({1, 4}, "pop", "foes")
addSpot({2, 4}, "pop", "foes")
addSpot({1, 5}, "pop", "foes")
addSpot({2, 5}, "pop", "foes")
addSpot({1, 6}, "pop", "foes")
addSpot({2, 6}, "pop", "foes")
addSpot({1, 7}, "pop", "foes")
addSpot({2, 7}, "pop", "foes")
addSpot({1, 8}, "pop", "foes")
addSpot({2, 8}, "pop", "foes")
addSpot({1, 9}, "pop", "foes")
addSpot({2, 9}, "pop", "foes")
addSpot({47, 31}, "pop", "foes")
addSpot({48, 31}, "pop", "foes")
addSpot({47, 32}, "pop", "foes")
addSpot({48, 32}, "pop", "foes")
addSpot({47, 33}, "pop", "foes")
addSpot({48, 33}, "pop", "foes")
addSpot({47, 34}, "pop", "foes")
addSpot({48, 34}, "pop", "foes")
addSpot({47, 35}, "pop", "foes")
addSpot({48, 35}, "pop", "foes")
addSpot({47, 36}, "pop", "foes")
addSpot({48, 36}, "pop", "foes")
addSpot({47, 37}, "pop", "foes")
addSpot({48, 37}, "pop", "foes")
addSpot({47, 38}, "pop", "foes")
addSpot({48, 38}, "pop", "foes")
addSpot({46, 4}, "pop", "foes")
addSpot({46, 5}, "pop", "foes")
addSpot({46, 6}, "pop", "foes")
addSpot({46, 7}, "pop", "foes")
addSpot({46, 8}, "pop", "foes")
addSpot({46, 9}, "pop", "foes")
addSpot({46, 10}, "pop", "foes")
addSpot({46, 11}, "pop", "foes")
addSpot({2, 31}, "pop", "foes")
addSpot({2, 32}, "pop", "foes")
addSpot({7, 7}, "pop", "defender")
addSpot({11, 4}, "pop", "defender")
addSpot({7, 13}, "pop", "defender")
addSpot({12, 26}, "pop", "defender")
addSpot({10, 40}, "pop", "defender")
addSpot({15, 37}, "pop", "defender")
addSpot({21, 32}, "pop", "defender")
addSpot({8, 46}, "pop", "defender")
addSpot({44, 41}, "pop", "defender")
addSpot({44, 42}, "pop", "defender")
addSpot({38, 39}, "pop", "defender")
addSpot({28, 33}, "pop", "defender")
addSpot({37, 32}, "pop", "defender")
addSpot({40, 28}, "pop", "defender")
addSpot({35, 19}, "pop", "defender")
addSpot({35, 12}, "pop", "defender")
addSpot({35, 9}, "pop", "defender")
addSpot({35, 4}, "pop", "defender")
addSpot({23, 4}, "pop", "defender")
addSpot({28, 3}, "pop", "defender")
addSpot({15, 0}, "pop", "foes")
addSpot({16, 0}, "pop", "foes")
addSpot({17, 0}, "pop", "foes")
addSpot({18, 0}, "pop", "foes")
addSpot({19, 0}, "pop", "foes")
addSpot({34, 0}, "pop", "foes")
addSpot({35, 0}, "pop", "foes")
addSpot({36, 0}, "pop", "foes")
addSpot({37, 0}, "pop", "foes")
addSpot({38, 0}, "pop", "foes")
addSpot({0, 40}, "pop", "foes")
addSpot({0, 41}, "pop", "foes")
addSpot({0, 42}, "pop", "foes")
addSpot({0, 43}, "pop", "foes")
addSpot({0, 44}, "pop", "foes")
addSpot({24, 32}, "pop", "player-attack")
addSpot({25, 32}, "pop", "player-attack")
addSpot({26, 36}, "pop", "defiler")
-- addZone section
addZone({23, 25, 23, 28}, "particle", "house_flamebeam")
addZone({22, 16, 22, 23}, "particle", "house_flamebeam")
addZone({23, 6, 23, 13}, "particle", "house_flamebeam")
addZone({13, 13, 13, 22}, "particle", "house_flamebeam")
addZone({17, 8, 24, 8}, "particle", "house_flamebeam")
addZone({26, 31, 36, 31}, "particle", "house_flamebeam")
addZone({33, 12, 33, 18}, "particle", "house_flamebeam")
-- ASCII map section
return [[
**************************************************
**************************************************
**************************************************
************************---------*****************
***********---*********--######-----**************
*********--------******---####-------*************
********----####--*****----1#--------*************
*******-----####--******-------##--***************
*******-###-2#3#--******------####-***************
*******-###------*********----7#8#--**************
*******-4##-----***********---------**************
*******-----*---************--------**************
*******----**---**************------**************
*******----**--*******--**************************
********--***********---**************************
********************---***************************
********************---***************************
**************************************************
*********************************--***************
*********************************---**************
*********************************-s-**************
*********************************---**************
************--********************--**************
************---*******---*************************
************-s-*******---*************************
************-s-*******--**************************
************---***********************************
*************--***********************************
***********************---**************--********
***********************-<-**********------********
***********************----*********-----*********
**********************-----*********---***********
*********************-------*******---************
********************---------******--*************
*******************----------*********************
******************------------********************
*****************--######-----********************
***************----#5#6##------*******************
**************-----#----#-------******************
************------###--###-------*****------******
**********-----------------------------------*****
********------tt.....---------ss-------------*****
******-------ttt~~~~..-------ssss------------*****
******-----tttt~~t.~~.-------^^^^------==-==--****
******-----ttt~~tt..~...----^^^^^^^---==___==-****
******------ttttttt.~~~....^^^^^^^^---=__Z__==****
********---------t-...~~~~^^^^^^^^^---=______=****
*************--------......ssssss-----========****
********************------------------************
**************************************************]] | gpl-3.0 |
hfjgjfg/eli25 | plugins/torrent_search.lua | 411 | 1622 | --[[ NOT USED DUE TO SSL ERROR
-- See https://getstrike.net/api/
local function strike_search(query)
local strike_base = 'http://getstrike.net/api/v2/torrents/'
local url = strike_base..'search/?phrase='..URL.escape(query)
print(url)
local b,c = http.request(url)
print(b,c)
local search = json:decode(b)
vardump(search)
if c ~= 200 then
return search.message
end
vardump(search)
local results = search.results
local text = 'Results: '..results
local results = math.min(results, 3)
for i=1,results do
local torrent = search.torrents[i]
text = text..torrent.torrent_title
..'\n'..'Seeds: '..torrent.seeds
..' '..'Leeches: '..torrent.seeds
..'\n'..torrent.magnet_uri..'\n\n'
end
return text
end]]--
local function search_kickass(query)
local url = 'http://kat.cr/json.php?q='..URL.escape(query)
local b,c = http.request(url)
local data = json:decode(b)
local text = 'Results: '..data.total_results..'\n\n'
local results = math.min(#data.list, 5)
for i=1,results do
local torrent = data.list[i]
local link = torrent.torrentLink
link = link:gsub('%?title=.+','')
text = text..torrent.title
..'\n'..'Seeds: '..torrent.seeds
..' '..'Leeches: '..torrent.leechs
..'\n'..link
--..'\n magnet:?xt=urn:btih:'..torrent.hash
..'\n\n'
end
return text
end
local function run(msg, matches)
local query = matches[1]
return search_kickass(query)
end
return {
description = "Search Torrents",
usage = "!torrent <search term>: Search for torrent",
patterns = {
"^!torrent (.+)$"
},
run = run
}
| gpl-2.0 |
abasshacker/abbasgh | plugins/bot_on_off.lua | 292 | 1641 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Robot is Online'
end
_config.disabled_channels[receiver] = false
save_config()
return "Robot is Online"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Robot is Offline"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "[!/]bot on" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'on' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver)
end
end
return {
description = "Robot Switch",
usage = {
"/bot on : enable robot in group",
"/bot off : disable robot in group" },
patterns = {
"^[!/]bot? (on)",
"^[!/]bot? (off)" },
run = run,
privileged = true,
--moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Grauberg_[S]/Zone.lua | 1 | 1117 | -----------------------------------
--
-- Zone: Grauberg_[S]
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Grauberg_[S]/TextIDs"] = nil;
require("scripts/zones/Grauberg_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/class/PartyMember.lua | 3 | 1588 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
require "mod.class.NPC"
require "mod.class.interface.PartyDeath"
module(..., package.seeall, class.inherit(mod.class.NPC, mod.class.interface.PartyDeath))
function _M:init(t, no_default)
mod.class.NPC.init(self, t, no_default)
-- Set correct AI
if self.ai ~= "party_member" and not self.no_party_ai then
self.ai_state.ai_party = self.ai
self.ai = "party_member"
end
end
function _M:tooltip(x, y, seen_by)
local str = mod.class.NPC.tooltip(self, x, y, seen_by)
if not str then return end
str:add(
true,
{"color", "TEAL"},
("Behavior: %s"):format(self.ai_tactic.type or "default"), true,
("Action radius: %d"):format(self.ai_state.tactic_leash),
{"color", "WHITE"}
)
return str
end
function _M:die(src, death_note)
return self:onPartyDeath(src, death_note)
end
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Metalworks/npcs/Lutia.lua | 5 | 1035 | -----------------------------------
-- Area: Metalworks
-- NPC: Lutia
-- Type: Standard NPC
-- @zone: 237
-- @pos: 24.076 -17 -33.060
--
-- 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(0x00ca);
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 |
NPLPackages/paracraft | script/kids/3DMapSystemApp/worlds/RegionMonitorPage.lua | 1 | 2963 | --[[
Title: RegionMonitorPage
Author(s): Leio
Date: 2009/9/27
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemApp/worlds/RegionMonitorPage.lua");
Map3DSystem.App.worlds.RegionMonitorPage.Show();
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemApp/worlds/RegionMonitor.lua");
local RegionMonitorPage = {
page = nil,
regionMonitor = nil,
isShow = false;
}
commonlib.setfield("Map3DSystem.App.worlds.RegionMonitorPage",RegionMonitorPage);
function RegionMonitorPage.Init()
local self = RegionMonitorPage;
self.page = document:GetPageCtrl();
end
function RegionMonitorPage.Show()
local self = RegionMonitorPage;
if(not self.isShow)then
self.ShowPage();
else
self.ClosePage();
end
end
function RegionMonitorPage.ShowPage()
local self = RegionMonitorPage;
self.isShow = true;
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/kids/3DMapSystemApp/worlds/RegionMonitorPage.html",
name = "RegionMonitorPage.ShowPage",
--app_key=MyCompany.Aries.app.app_key,
app_key=MyCompany.Taurus.app.app_key,
isShowTitleBar = true,
DestroyOnClose = false, -- prevent many ViewProfile pages staying in memory
--style = CommonCtrl.WindowFrame.ContainerStyle,
text = "",
zorder = 1,
directPosition = true,
align = "_lt",
x = 0,
y = 0,
width = 600,
height = 300,
});
if(not self.regionMonitor)then
self.regionMonitor = Map3DSystem.App.worlds.RegionMonitor:new{
};
self.regionMonitor:AddEventListener("move",RegionMonitorPage.Update_Custom);
self.regionMonitor:AddEventListener("sound",RegionMonitorPage.Update_Custom);
self.regionMonitor:AddEventListener("test",RegionMonitorPage.Update_Custom);
else
self.regionMonitor:Resume();
end
end
function RegionMonitorPage.Update_Custom(args)
local self = RegionMonitorPage;
if(self.page and args)then
local type = args.event_type;
local s = string.format("event_type = %s,argb = %s,r = %s,g = %s,b = %s,a = %s,CurrentRegionFilepath = %s,CurrentRegionName = %s,NumOfRegions = %s",
args.event_type or "",
tostring(args.argb) or "",
tostring(args.r) or "",
tostring(args.g) or "",
tostring(args.b) or "",
tostring(args.a) or "",
tostring(args.CurrentRegionFilepath) or "",
tostring(args.CurrentRegionName) or "",
tostring(args.NumOfRegions) or "");
if(type == "move")then
self.page:SetValue("move_ctl",s);
elseif(type == "sound")then
self.page:SetValue("sound_ctl",s);
elseif(type == "test")then
self.page:SetValue("custom_ctl",s);
end
end
end
function RegionMonitorPage.ClosePage()
local self = RegionMonitorPage;
self.isShow = false;
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name="RegionMonitorPage.ShowPage",
app_key=MyCompany.Taurus.app.app_key,
bShow = false,bDestroy = false,});
if(self.regionMonitor)then
self.regionMonitor:Pause();
end
end | gpl-2.0 |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/libs/nixio/docsrc/nixio.Socket.lua | 157 | 6508 | --- Socket Object.
-- Supports IPv4, IPv6 and UNIX (POSIX only) families.
-- @cstyle instance
module "nixio.Socket"
--- Get the local address of a socket.
-- @class function
-- @name Socket.getsockname
-- @return IP-Address
-- @return Port
--- Get the peer address of a socket.
-- @class function
-- @name Socket.getpeername
-- @return IP-Address
-- @return Port
--- Bind the socket to a network address.
-- @class function
-- @name Socket.bind
-- @usage This function calls getaddrinfo() and bind() but NOT listen().
-- @usage If <em>host</em> is a domain name it will be looked up and bind()
-- tries the IP-Addresses in the order returned by the DNS resolver
-- until the bind succeeds.
-- @usage UNIX sockets ignore the <em>port</em>,
-- and interpret <em>host</em> as a socket path.
-- @param host Host (optional, default: all addresses)
-- @param port Port or service description
-- @return true
--- Connect the socket to a network address.
-- @class function
-- @name Socket.connect
-- @usage This function calls getaddrinfo() and connect().
-- @usage If <em>host</em> is a domain name it will be looked up and connect()
-- tries the IP-Addresses in the order returned by the DNS resolver
-- until the connect succeeds.
-- @usage UNIX sockets ignore the <em>port</em>,
-- and interpret <em>host</em> as a socket path.
-- @param host Hostname or IP-Address (optional, default: localhost)
-- @param port Port or service description
-- @return true
--- Listen for connections on the socket.
-- @class function
-- @name Socket.listen
-- @param backlog Length of queue for pending connections
-- @return true
--- Accept a connection on the socket.
-- @class function
-- @name Socket.accept
-- @return Socket Object
-- @return Peer IP-Address
-- @return Peer Port
--- Send a message on the socket specifying the destination.
-- @class function
-- @name Socket.sendto
-- @usage <strong>Warning:</strong> It is not guaranteed that all data
-- in the buffer is written at once.
-- You have to check the return value - the number of bytes actually written -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage Unlike standard Lua indexing the lowest offset and default is 0.
-- @param buffer Buffer holding the data to be written.
-- @param host Target IP-Address
-- @param port Target Port
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @return number of bytes written
--- Send a message on the socket.
-- This function is identical to sendto except for the missing destination
-- paramters. See the sendto description for a detailed description.
-- @class function
-- @name Socket.send
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @see Socket.sendto
-- @return number of bytes written
--- Send a message on the socket (This is an alias for send).
-- See the sendto description for a detailed description.
-- @class function
-- @name Socket.write
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @see Socket.sendto
-- @return number of bytes written
--- Receive a message on the socket including the senders source address.
-- @class function
-- @name Socket.recvfrom
-- @usage <strong>Warning:</strong> It is not guaranteed that all requested data
-- is read at once.
-- You have to check the return value - the length of the buffer actually read -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage The length of the return buffer is limited by the (compile time)
-- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default).
-- Any read request greater than that will be safely truncated to this value.
-- @param length Amount of data to read (in Bytes).
-- @return buffer containing data successfully read
-- @return host IP-Address of the sender
-- @return port Port of the sender
--- Receive a message on the socket.
-- This function is identical to recvfrom except that it does not return
-- the sender's source address. See the recvfrom description for more details.
-- @class function
-- @name Socket.recv
-- @param length Amount of data to read (in Bytes).
-- @see Socket.recvfrom
-- @return buffer containing data successfully read
--- Receive a message on the socket (This is an alias for recv).
-- See the recvfrom description for more details.
-- @class function
-- @name Socket.read
-- @param length Amount of data to read (in Bytes).
-- @see Socket.recvfrom
-- @return buffer containing data successfully read
--- Close the socket.
-- @class function
-- @name Socket.close
-- @return true
--- Shut down part of a full-duplex connection.
-- @class function
-- @name Socket.shutdown
-- @param how (optional, default: rdwr) ["rdwr", "rd", "wr"]
-- @return true
--- Get the number of the filedescriptor.
-- @class function
-- @name Socket.fileno
-- @return file descriptor number
--- Set the blocking mode of the socket.
-- @class function
-- @name Socket.setblocking
-- @param blocking (boolean)
-- @return true
--- Set a socket option.
-- @class function
-- @name Socket.setopt
-- @param level Level ["socket", "tcp", "ip", "ipv6"]
-- @param option Option ["keepalive", "reuseaddr", "sndbuf", "rcvbuf",
-- "priority", "broadcast", "linger", "sndtimeo", "rcvtimeo", "dontroute",
-- "bindtodevice", "error", "oobinline", "cork" (TCP), "nodelay" (TCP),
-- "mtu" (IP, IPv6), "hdrincl" (IP), "multicast_ttl" (IP), "multicast_loop"
-- (IP, IPv6), "multicast_if" (IP, IPv6), "v6only" (IPv6), "multicast_hops"
-- (IPv6), "add_membership" (IP, IPv6), "drop_membership" (IP, IPv6)]
-- @param value Value
-- @return true
--- Get a socket option.
-- @class function
-- @name Socket.getopt
-- @param level Level ["socket", "tcp", "ip", "ipv6"]
-- @param option Option ["keepalive", "reuseaddr", "sndbuf", "rcvbuf",
-- "priority", "broadcast", "linger", "sndtimeo", "rcvtimeo", "dontroute",
-- "bindtodevice", "error", "oobinline", "cork" (TCP), "nodelay" (TCP),
-- "mtu" (IP, IPv6), "hdrincl" (IP), "multicast_ttl" (IP), "multicast_loop"
-- (IP, IPv6), "multicast_if" (IP, IPv6), "v6only" (IPv6), "multicast_hops"
-- (IPv6), "add_membership" (IP, IPv6), "drop_membership" (IP, IPv6)]
-- @return Value | gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/greedie.lua | 1 | 1178 | -----------------------------------------
-- ID: 4500
-- Item: greedie
-- Food Effect: 0Min, Mithra only
-----------------------------------------
-- Dexterity 1
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:getRace() ~= 7) then
result = 247;
elseif (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,0,0,4500);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_MND, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_MND, -3);
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Mhaura/npcs/Zexu.lua | 3 | 1260 | -----------------------------------
-- Area: Mhaura
-- NPC: Zexu
-- Involved in Quests: The Sand Charm
-- @zone 249
-- @pos 30 -8 25
-----------------------------------
require("scripts/globals/settings");
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:getVar("theSandCharmVar") == 1) then
player:startEvent(0x007b); -- During quest "The Sand Charm" - 1st dialog
else
player:startEvent(0x0079); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x007b) then
player:setVar("theSandCharmVar",2);
end
end; | gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/OnlineStore/OnlineStore.lua | 1 | 5171 | --[[
Title: OnlineStore
Author(s): LiXizhi
Date: 2019/8/13
Desc: online store at: https://keepwork.com/p/comp/system?port=8099
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/OnlineStore/OnlineStore.lua");
local OnlineStore = commonlib.gettable("MyCompany.Aries.Game.Tasks.OnlineStore");
local task = OnlineStore:new():Init();
task:Run();
-------------------------------------------------------
]]
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager")
local OnlineStore = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Task"), commonlib.gettable("MyCompany.Aries.Game.Tasks.OnlineStore"));
-- this is always a top level task.
OnlineStore.is_top_level = true;
OnlineStore.portNumber = "8099"
function OnlineStore:ctor()
end
function OnlineStore:Init()
return self;
end
function OnlineStore.GetOnlineStoreUrl(name)
local host = GameLogic.GetFilters():apply_filters('get_keepwork_url');
local token = System.User.keepworktoken or '';
local url = format("%s/p/comp/system?port=%s&token=%s", host, tostring(OnlineStore.portNumber or 8099), token);
if System.os.GetPlatform() == 'mac' or System.os.GetPlatform() == 'android' then
url = format("%s/p/comp/system?type=protocol&port=%s&token=%s", host, tostring(OnlineStore.portNumber or 8099), token);
end
return GameLogic.GetFilters():apply_filters("OnlineStore.CustomOnlineStoreUrl", url, name);
end
local page;
function OnlineStore.InitPage(Page)
page = Page;
end
-- get current instance
function OnlineStore.GetInstance()
return curInstance;
end
function OnlineStore:RefreshPage()
if(page) then
page:Refresh(0.01);
end
end
function OnlineStore:Run(name)
local projectId = tostring(GameLogic.options:GetProjectId());
if (projectId == "10373") then
_guihelper.MessageBox(L"当前世界无法使用元件库功能。");
return;
end
self.finished = true;
self:ShowPage(true, name);
end
function OnlineStore:ShowPage(bShow, name)
if(false) then
if(bShow) then
GameLogic.RunCommand(format("/open -name OnlineStore -title %s -width 1020 -height 680 -alignment _ct %s", L"元件库", OnlineStore.GetOnlineStoreUrl(name)));
end
return
end
if System.os.GetPlatform() == 'win32' or System.os.GetPlatform() == 'android' then
NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.lua");
local NplBrowserLoaderPage = commonlib.gettable("NplBrowser.NplBrowserLoaderPage");
NplBrowserLoaderPage.CheckOnce()
if not NplBrowserLoaderPage.IsLoaded() then
ParaGlobal.ShellExecute("open", OnlineStore.GetOnlineStoreUrl(name), "", "", 1);
return
end
end
-- use mcml window
if(not page) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/NPLWebServer.lua");
local NPLWebServer = commonlib.gettable("MyCompany.Aries.Game.Network.NPLWebServer");
local bStarted, site_url = NPLWebServer.CheckServerStarted(function(bStarted, site_url)
if(bStarted) then
OnlineStore.portNumber = site_url:match("%:(%d+)") or OnlineStore.portNumber;
GameLogic.GetFilters():add_filter("OnShowEscFrame", OnlineStore.OnShowEscFrame);
GameLogic.GetFilters():add_filter("ShowExitDialog", OnlineStore.OnClose);
GameLogic.GetFilters():add_filter("OnInstallModel", OnlineStore.OnClose);
NPL.load("(gl)script/ide/System/Windows/Screen.lua");
local Screen = commonlib.gettable("System.Windows.Screen");
local alignment, x, y, width, height = "_fi", 20, 30, 20, 64;
if(Screen:GetWidth() >= 1020 and Screen:GetHeight() >= 720) then
alignment, width, height = "_ct", 1020, 680;
x, y = -width/2, -height/2;
end
local url = "script/apps/Aries/Creator/Game/Tasks/OnlineStore/OnlineStore.html?rand=" .. os.time();
local customUrl = GameLogic.GetFilters():apply_filters("OnlineStore.getPageParamUrl", url, name);
local params = {
url = customUrl,
name = "OnlineStore.ShowPage",
isShowTitleBar = false,
DestroyOnClose = false,
bToggleShowHide = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
bShow = bShow,
click_through = false,
zorder = 10,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = alignment,
x = x,
y = y,
width = width,
height = height,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
page = params._page;
if(params._page) then
params._page:CallMethod("nplbrowser_store", "SetVisible", bShow~=false);
params._page.OnClose = function()
if(params._page) then
params._page:CallMethod("nplbrowser_store", "SetVisible", false);
end
page = nil;
end
end
end
end)
else
if(bShow == false) then
page:CloseWindow();
else
page:Refresh(0.1);
end
end
end
function OnlineStore.OnShowEscFrame(bShow)
if(bShow ~= false) then
OnlineStore.OnClose()
end
end
function OnlineStore.OnClose()
if(page) then
page:CloseWindow();
end
end
| gpl-2.0 |
EliasJMote/Endless-Runner | main.lua | 1 | 4624 | -----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
-- Endless runner game with grappling hook mechanics
--
-- In this game, a knight runs along an endless strip to land (simulated by
-- having objects scroll from right to left). Background objects will utilize
-- parallax scrolling to create an illusion of depth. There will be a few layers of
-- clouds scrolling by, as well as a distant moon that will stay still.
--
-- During the game, spikes will appear along the ground that will kill the knight (player)
-- if he touches them. In addition, small walls made of blocks will appear to block the
-- knights path. To get past these obstacles, the player must tap the screen at particular
-- times to avoid these traps.
--
-- The first time the player taps the screen, the knight will perform a short jump. The
-- second time the player taps the screen (before the knight hits the ground), the knight
-- will shoot out a chain at a 45 degree angle with a small spike attached to the end of it.
--
-- When the spike at the end of the chain hits certain grapple points (such as small floating
-- rings, for instance), the knight will swing from the grapple point utilizing a rope joint.
-- This keeps the player at a max distance from the point but still allow the knight to have
-- some momentum so that they player can launch the knight pass the obstacles.
--
-- Grapple joints in the game will vary. Some will be simple static objects that scroll slowly
-- to the left, while others may be more complicated, such as points attached to one another
-- with pulley joints. This will force the player to use different strategies to overcome
-- each obstacle.
--
-- As the game is an endless runner, there is no "winning" the game so to speak. Instead,
-- the farther along in the game the player gets, the greater his/her score will be. The
-- score will increase constantly over time. These scores may be saved in a high score
-- table that the player can access in a different view.
--
-- The game will have a few different screens: at minimum, a title screen, a gameplay screen,
-- and an options screen. If time permits, I will also implement a high score screen.
-- Final project requirements:
--
-- Physics:
-- Bodies: at least 2 different types (e.g. static, dynamic) and 2 different shapes
-- (e.g. rectangular, circular)
-- Collision event detection and actions (at least 2 different ones)
-- Joints (at least 3 different types)
--
-- Animation
-- Sprite animation or use of image sheets
-- Changing text display (e.g. score readout)
--
-- Touch and Input:
-- Touch events (touch or tap)
--
-- Sound:
-- Sound effects (at least 3 different ones)
-- Background music with an on/off switch or volume slider
--
-- Multiple Views:
-- Composer multiscene management (at least 3 scenes)
-- Hide/show UI objects
--
-- Widgets:
-- Button, Slider and/or Switch (any combination 5 points max)
-- Native text field
--
-- Data Model and Files:
-- Load resource data from file
-- User data load/save
--
-- Deploy and Demo:
-- Show deployment on Android or iOS device
-- Demo app and show some source code in front of class (during the last week)
globalVariables = {
musicVolume = 50,
sfxVolume = 50,
topScore = 0
}
-- include Corona's "composer" library
local composer = require( "composer" )
local scene = composer.newScene()
-- load required Corona modules
local json = require( "json" )
-- Global functions
-- Save the string str to a data file with the given path name.
-- Return true if successful, false if failure.
function writeDataFile(str, pathName, mode)
local file = io.open(pathName, mode or "w")
if file then
file:write(str)
io.close(file)
print("Saved to: " .. pathName)
return true
end
return false
end
-- Load the contents of a data file with the given path name.
-- Return the contents as a string or nil if failure (e.g. file does not exist).
function readDataFile(pathName)
local str = nil
local file = io.open(pathName, "r")
if file then
str = file:read("*a") -- read entire file as a single string
io.close(file)
if str then
print("Loaded from: " .. pathName)
end
end
return str
end
local jsonSettings = readDataFile("user_preferences.txt")
local settings = json.decode(jsonSettings)
globalVariables.musicVolume = settings.musicVolume
globalVariables.sfxVolume = settings.sfxVolume
-- hide the status bar
display.setStatusBar( display.HiddenStatusBar )
-- load title screen
composer.gotoScene( "title_screen" ) | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Davoi/npcs/Disused_Well.lua | 1 | 1321 | -----------------------------------
-- Area: Davoi
-- NPC: Disused Well
-- Involved in Quest: A Knight's Test
-- @zone 149
-- @pos -221 2 -293
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(KNIGHTS_SOUL) == false and player:hasKeyItem(BOOK_OF_TASKS) and player:hasKeyItem(BOOK_OF_THE_WEST) and player:hasKeyItem(BOOK_OF_THE_EAST)) then
player:addKeyItem(KNIGHTS_SOUL);
player:messageSpecial(KEYITEM_OBTAINED, KNIGHTS_SOUL);
else
player:messageSpecial(YOU_SEE_NOTHING);
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 |
groupforspeed/API-WaderTG | plugins/azan.lua | 10 | 3158 | --[[
#
# @WaderTGTeam
# @WaderTGTeam
#
]]
do
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"
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
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
function run(msg, matches)
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
local receiver = get_receiver(msg)
local city = matches[1]
if matches[1] == 'azan' 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..'\n\n@WaderTGTeam'
if string.match(text, '0') then text = string.gsub(text, '0', '۰') end
if string.match(text, '1') then text = string.gsub(text, '1', '۱') end
if string.match(text, '2') then text = string.gsub(text, '2', '۲') end
if string.match(text, '3') then text = string.gsub(text, '3', '۳') end
if string.match(text, '4') then text = string.gsub(text, '4', '۴') end
if string.match(text, '5') then text = string.gsub(text, '5', '۵') end
if string.match(text, '6') then text = string.gsub(text, '6', '۶') end
if string.match(text, '7') then text = string.gsub(text, '7', '۷') end
if string.match(text, '8') then text = string.gsub(text, '8', '۸') end
if string.match(text, '9') then text = string.gsub(text, '9', '۹') end
return text
end
return {
patterns = {"^[#/!][Aa]zan (.*)$","^[#/!](azan)$"},
run = run
}
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/serving_of_medicinal_quus.lua | 1 | 1337 | -----------------------------------------
-- ID: 4294
-- Item: serving_of_medicinal_quus
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 1
-- Mind -1
-- Ranged ACC % 7
-- Ranged ACC Cap 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,0,4294);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/slice_of_roast_mutton.lua | 1 | 1331 | -----------------------------------------
-- ID: 4437
-- Item: slice_of_roast_mutton
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength 3
-- Intelligence -1
-- Attack % 27
-- Attack Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,0,4437);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 3);
target:addMod(MOD_INT, -1);
target:addMod(MOD_FOOD_ATTP, 27);
target:addMod(MOD_FOOD_ATT_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 3);
target:delMod(MOD_INT, -1);
target:delMod(MOD_FOOD_ATTP, 27);
target:delMod(MOD_FOOD_ATT_CAP, 30);
end;
| gpl-3.0 |
adde88/Nerdpack-Zylla | fakeunits.lua | 1 | 5034 | local _, Zylla = ...
local _G = _G
local NeP = _G.NeP
local function ClassRange(target)
if ( NeP.DSL:Get('range')(target, 'player') <= NeP.DSL:Get('class_range')() )
or ( NeP.DSL:Get('inmelee')(target) and NeP.DSL:Get('class_range')() == 5 ) then
return true
end
return false
end
-- Healing stuff
NeP.FakeUnits:Add('healingCandidate', function(nump)
local tempTable = {}
local num = nump or 1
for _, Obj in pairs(NeP.OM:Get('Friendly')) do
if _G.UnitPlayerOrPetInParty(Obj.key)
or _G.UnitIsUnit('player', Obj.key) then
local healthRaw = Zylla.GetPredictedHealth(Obj.key)
local maxHealth = _G.UnitHealthMax(Obj.key)
local healthPercent = (healthRaw / maxHealth) * 100
tempTable[#tempTable+1] = {
name = Obj.name,
key = Obj.key,
health = healthPercent,
}
end
end
table.sort( tempTable, function(a,b) return a.health < b.health end )
return tempTable[num] and tempTable[num].key
end)
-- Customized for Windwalker Rotation
NeP.FakeUnits:Add('Zylla_sck', function(debuff)
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) )
and (NeP.DSL:Get('combat')(Obj.key) or Obj.isdummy)
and (NeP.DSL:Get('infront')(Obj.key) and NeP.DSL:Get('inMelee')(Obj.key)) then
local _,_,_,_,_,_,debuffDuration = _G.UnitDebuff(Obj.key, debuff, nil, 'PLAYER')
if not debuffDuration or debuffDuration - _G.GetTime() < 1.5 then
--print("Zylla_sck: returning "..Obj.name.." ("..Obj.key.." - "..Obj.guid..' :'..time()..")");
return Obj.key
end
end
end
end)
-- Highest Health Enemy
NeP.FakeUnits:Add({'highestenemy', 'higheste', 'he'}, function(num)
local tempTable = {}
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) )
and NeP.DSL:Get('combat')(Obj.key)
and NeP.DSL:Get('alive')(Obj.key)
and ClassRange(Obj.key) then
tempTable[#tempTable+1] = {
name = Obj.name,
key = Obj.key,
health = NeP.DSL:Get("health")(Obj.key)
}
end
end
table.sort( tempTable, function(a,b) return a.health > b.health end )
return tempTable[num] and tempTable[num].key
end)
-- Lowest Enemy (CUSTOMIZED TO WORK WITH MY CR'S)
NeP.FakeUnits:Add({'z.lowestenemy', 'z.loweste', 'z.le'}, function(num)
local tempTable = {}
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) )
and NeP.DSL:Get('combat')(Obj.key)
and NeP.DSL:Get('alive')(Obj.key)
and ClassRange(Obj.key) then
tempTable[#tempTable+1] = {
key = Obj.key,
health = NeP.DSL:Get("health")(Obj.key)
}
end
end
table.sort( tempTable, function(a,b) return a.health < b.health end )
return tempTable[num] and tempTable[num].key
end)
-- Feral Druid Stuff XXX: Remember to set the 'ptf_timer' variable in your UI Settings.
NeP.FakeUnits:Add({'nobleedenemy', 'nobleede'}, function()
local ptf_timer = tonumber(NeP.DSL:Get('UI')(nil, 'ptftimer_spin'))
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) ) then
local rip_duration = tonumber(NeP.DSL:Get('debuff.duration')(Obj.key, 'Rip'))
local rake_duration = tonumber(NeP.DSL:Get('debuff.duration')(Obj.key, 'Rake'))
local thrash_duration = tonumber(NeP.DSL:Get('debuff.duration')(Obj.key, 'Thrash'))
if (NeP.DSL:Get('inFront')(Obj.key) and NeP.DSL:Get('inMelee')(Obj.key))
and rip_duration < ptf_timer
and rake_duration < ptf_timer
and thrash_duration < ptf_timer
and ClassRange(Obj.key) then
return Obj.key
end
end
end
end)
-- Nearest Enemy
NeP.FakeUnits:Add({'nearestenemy', 'neareste', 'ne'}, function(num)
local tempTable = {}
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) )
and ClassRange(Obj.key) then
tempTable[#tempTable+1] = {
name = Obj.name,
key = Obj.key,
range = NeP.DSL:Get("rangefrom")('player', Obj.key)
}
end
end
table.sort( tempTable, function(a,b) return a.range < b.range end )
return tempTable[num] and tempTable[num].key
end)
-- Furthest Enemy (Within 60 yd)
NeP.FakeUnits:Add({'furthestenemy', 'furtheste', 'fe'}, function(num)
local tempTable = {}
for _, Obj in pairs(NeP.OM:Get('Enemy')) do
if ( _G.UnitExists(Obj.key) and _G.UnitIsVisible(Obj.key) )
and ClassRange(Obj.key) then
tempTable[#tempTable+1] = {
name = Obj.name,
key = Obj.key,
range = NeP.DSL:Get("rangefrom")('player', Obj.key)
}
end
end
table.sort( tempTable, function(a,b) return a.range > b.range end )
return tempTable[num] and tempTable[num].key
end)
| mit |
madpilot78/ntopng | scripts/lua/modules/country_utils.lua | 1 | 1574 | require "lua_utils"
-- Get from redis the throughput type bps or pps
local throughput_type = getThroughputType()
local now = os.time()
function country2record(ifId, country)
local record = {}
record["key"] = tostring(country["country"])
local country_link = "<A HREF='"..ntop.getHttpPrefix()..'/lua/hosts_stats.lua?country='..country["country"].."' title='"..country["country"].."'>"..country["country"]..'</A>'
record["column_id"] = getFlag(country["country"]).."  " .. country_link
record["column_hosts"] = country["num_hosts"]..""
record["column_score"] = country["score"]
record["column_since"] = secondsToTime(now - country["seen.first"] + 1)
local sent2rcvd = round((country["egress"] * 100) / (country["egress"] + country["ingress"]), 0)
record["column_breakdown"] = "<div class='progress'><div class='progress-bar bg-warning' style='width: "
.. sent2rcvd .."%;'>Sent</div><div class='progress-bar bg-success' style='width: " .. (100-sent2rcvd) .. "%;'>Rcvd</div></div>"
if(throughput_type == "pps") then
record["column_thpt"] = pktsToSize(country["throughput_pps"])
else
record["column_thpt"] = bitsToSize(8*country["throughput_bps"])
end
record["column_traffic"] = bytesToSize(country["bytes"])
record["column_chart"] = ""
if areCountryTimeseriesEnabled(ifId) then
record["column_chart"] = '<A HREF="'..ntop.getHttpPrefix()..'/lua/country_details.lua?country='..country["country"]..'&page=historical"><i class=\'fas fa-chart-area fa-lg\'></i></A>'
end
return record
end
| gpl-3.0 |
metal-bot/metal | metal.lua | 1 | 10460 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"web_shot",
"addplug",
"add-plugins",
"tophoto",
"banhammer",
"stats",
"calculator",
"echo",
"id",
"Auto_Leave",
"google",
"weather",
"lock_share",
"lock_media",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"plugins",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin"
},
sudo_users = {53406884,0,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[ELT v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
telegram.me/elt_bot1
Our team!
Alphonse (@Iwals)
aryan_ebli$ (@aryanes81)
amir.pga (@amir_pga)
RADDY (@R_A_D_D_Y)
SAM.PGA (@SAmPGA)
Special thanks to:
R_a_d_d_y
amir.pga
sam_pga
aryan_ebli$
Our channels:
English: @elt_bot1
Persian: @elt_bot1
]],
help_text_realm = [[
Realm Commands:
!creategroup [name]
Create a group
!createrealm [name]
Create a realm
!setname [name]
Set realm name
!setabout [group_id] [text]
Set a group's about text
!setrules [grupo_id] [text]
Set a group's rules
!lock [grupo_id] [setting]
Lock a group's setting
!unlock [grupo_id] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [grupo_id]
Kick all memebers and delete group
!kill realm [realm_id]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
» Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
Return group id or user id
!help
Get commands list
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules [text]
Set [text] as rules
!set about [text]
Set [text] as about
!settings
Returns group settings
!newlink
Create/revoke your group link
!link
Returns group link
!owner
Returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] [text]
Save [text] as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
Returns user id
!log
Will return group logs
!banlist
Will return group ban list
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/engines/default/engine/class.lua | 2 | 10968 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
module("class", package.seeall)
local base = _G
local run_inherited = {}
local function search(k, plist)
for i=1, #plist do
local v = plist[i][k] -- try `i'-th superclass
if v then return v end
end
end
function make(c)
setmetatable(c, {__index=_M})
c.new = function(...)
local obj = {}
obj.__CLASSNAME = c._NAME
setmetatable(obj, {__index=c})
if obj.init then obj:init(...) end
return obj
end
return c
end
local skip_key = {init=true, _NAME=true, _M=true, _PACKAGE=true, new=true, _BASES=true, castAs=true}
function inherit(...)
local bases = {...}
return function(c)
c._BASES = bases
-- Recursive inheritance caching
-- Inheritance proceeds from the first to last argument, so if the first and last base classes share a key the value will match the last base class
if #bases > 1 then
local completed_bases = {}
-- local inheritance_mapper = {}
local cache_inheritance
cache_inheritance = function(c, base)
-- Only cache a base class once
if not completed_bases[base] then
-- Recurse first so we replace those values
if base._BASES and type(base._BASES) == "table" then
for i, _base in ipairs(base._BASES) do
cache_inheritance(c, _base)
end
end
-- Cache all the immediate variables
-- local ncopied = 0
for k, e in pairs(base) do
if not skip_key[k] and (base[k] ~= nil) then
-- if c[k] ~= nil then
-- print(("INHERIT: *WARNING* replacing interface value %s (%s) from %s with (%s) from %s"):format(k, tostring(c[k]), inheritance_mapper[k], tostring(base[k]), base._NAME))
-- else
-- print(("INHERIT: caching interface value %s (%s) from %s to %s"):format(k, tostring(e), base._NAME, c._NAME))
-- end
c[k] = base[k]
-- inheritance_mapper[k] = base._NAME
-- ncopied = ncopied + 1
end
end
-- print(("INHERIT: cached %d values from %s to %s"):format(ncopied, base._NAME, c._NAME))
completed_bases[base] = true
completed_bases[#completed_bases+1] = base
end
end
local i = 1
while i <= #bases do
-- print(("INHERIT: base class #%d, %s"):format(i, bases[i]._NAME))
cache_inheritance(c, bases[i])
i = i + 1
end
-- print(("INHERIT: recursed through %d base classes for %s"):format(#completed_bases, c._NAME))
end
setmetatable(c, {__index=bases[1]})
c.new = function(...)
local obj = {}
obj.__CLASSNAME = c._NAME
setmetatable(obj, {__index=c})
if obj.init then obj:init(...) end
return obj
end
c.castAs = function(o)
o.__CLASSNAME = c._NAME
setmetatable(o, {__index=c})
end
if c.inherited then
run_inherited[#run_inherited+1] = function()
local i = 1
while i <= #bases do
c:inherited(bases[i], i)
i = i + 1
end
end
end
return c
end
end
function _M:importInterface(base)
for k, e in pairs(base) do
if not skip_key[k] and (base[k] ~= nil) then
self[k] = base[k]
end
end
end
function _M:getClassName()
return self.__CLASSNAME
end
function _M:getClass()
return getmetatable(self).__index
end
function _M:runInherited()
for _, f in ipairs(run_inherited) do
f()
end
end
local function clonerecurs(d)
local n = {}
for k, e in pairs(d) do
local nk, ne = k, e
if type(k) == "table" and not k.__CLASSNAME then nk = clonerecurs(k) end
if type(e) == "table" and not e.__CLASSNAME then ne = clonerecurs(e) end
n[nk] = ne
end
return n
end
--[[
local function cloneadd(dest, src)
for k, e in pairs(src) do
local nk, ne = k, e
if type(k) == "table" then nk = cloneadd(k) end
if type(e) == "table" then ne = cloneadd(e) end
dest[nk] = ne
end
end
]]
function _M:clone(t)
local n = clonerecurs(self)
if t then
-- error("cloning mutation not yet implemented")
-- cloneadd(n, t)
for k, e in pairs(t) do n[k] = e end
end
setmetatable(n, getmetatable(self))
if n.cloned then n:cloned(self) end
return n
end
local function clonerecursfull(clonetable, d, noclonecall, use_saveinstead)
if use_saveinstead and d.__CLASSNAME and d.__SAVEINSTEAD then
d = d.__SAVEINSTEAD
if clonetable[d] then return d, 1 end
end
local nb = 0
local add
local n = {}
clonetable[d] = n
local k, e = next(d)
while k do
local nk, ne = k, e
if clonetable[k] then nk = clonetable[k]
elseif type(k) == "table" then nk, add = clonerecursfull(clonetable, k, noclonecall, use_saveinstead) nb = nb + add
end
if clonetable[e] then ne = clonetable[e]
elseif type(e) == "table" and (type(k) ~= "string" or k ~= "__threads") then ne, add = clonerecursfull(clonetable, e, noclonecall, use_saveinstead) nb = nb + add
end
n[nk] = ne
k, e = next(d, k)
end
setmetatable(n, getmetatable(d))
if not noclonecall and n.cloned and n.__CLASSNAME then n:cloned(d) end
if n.__CLASSNAME then nb = nb + 1 end
return n, nb
end
--- Clones the object, all subobjects without cloning twice a subobject
-- @return the clone and the number of cloned objects
function _M:cloneFull(t)
local clonetable = {}
local n = clonerecursfull(clonetable, self, nil, nil)
if t then
for k, e in pairs(t) do n[k] = e end
end
return n
-- return core.serial.cloneFull(self)
end
--- Clones the object, all subobjects without cloning twice a subobject
-- Does not invoke clone methods as this is not for reloading, just for saving
-- @return the clone and the number of cloned objects
function _M:cloneForSave()
local clonetable = {}
return clonerecursfull(clonetable, self, true, true)
-- return core.serial.cloneFull(self)
end
--- Replaces the object with an other, by copying (not deeply)
function _M:replaceWith(t)
if self.replacedWith then self:replacedWith(false, t) end
-- Delete fields
while next(self) do
self[next(self)] = nil
end
for k, e in pairs(t) do
self[k] = e
end
setmetatable(self, getmetatable(t))
if self.replacedWith then self:replacedWith(true) end
end
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Hooks & Events system
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
local _hooks = {hooks={}, list={}}
local _current_hook_dir = nil
function _M:setCurrentHookDir(dir)
_current_hook_dir = dir
end
function _M:bindHook(hook, fct)
if type(fct) == "string" and _current_hook_dir then
local f, err = loadfile(_current_hook_dir..fct..".lua")
if not f then error(err) end
local ok, hook = pcall(f)
if not ok then error(hook) end
fct = hook
end
_hooks.list[hook] = _hooks.list[hook] or {}
table.insert(_hooks.list[hook], fct)
local sfct = [[return function(l, self, data) local ok=false]]
for i, fct in ipairs(_hooks.list[hook]) do
sfct = sfct..([[ if l[%d](self, data) then ok=true end]]):format(i)
end
sfct = sfct..[[ return ok end]]
local f, err = loadstring(sfct)
if not f then error(err) end
_hooks.hooks[hook] = f()
end
function _M:triggerHook(hook)
local h = hook[1]
if not _hooks.hooks[h] then return end
return _hooks.hooks[h](_hooks.list[h], self, hook)
end
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- LOAD & SAVE
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
__zipname_zf_store = {}
function _M:save(filter, allow)
filter = filter or {}
if self._no_save_fields then table.merge(filter, self._no_save_fields) end
if not allow then
filter.new = true
filter._no_save_fields = true
filter._mo = true
filter._last_mo = true
filter._mo_final = true
filter._hooks = true
else
filter.__CLASSNAME = true
end
local mt = getmetatable(self)
setmetatable(self, {})
local savefile = engine.Savefile.current_save
local s = core.serial.new(
-- Zip to write to
savefile.current_save_zip,
-- Namer
function(t) return savefile:getFileName(t) end,
-- Processor
function(t) savefile:addToProcess(t) end,
-- Allowed table
allow and filter or nil,
-- Disallowed table
not allow and filter or nil,
-- 2nd disallowed table
self._no_save_fields
)
s:toZip(self)
setmetatable(self, mt)
end
_M.LOAD_SELF = {}
local function deserialize(string, src)
local f, err = loadstring(string)
if err then print("error deserializing", string, err) end
setfenv(f, {
setLoaded = function(name, t)
-- print("[setLoaded]", name, t)
engine.Savefile.current_save.loaded[name] = t
end,
loadstring = loadstring,
loadObject = function(n)
if n == src then
return _M.LOAD_SELF
else
return engine.Savefile.current_save:loadReal(n)
end
end,
})
return f()
end
function load(str, delayloading)
local obj = deserialize(str, delayloading)
if obj then
-- print("setting obj class", obj.__CLASSNAME)
setmetatable(obj, {__index=require(obj.__CLASSNAME)})
if obj.loaded then
-- print("loader found for class", obj, obj.__CLASSNAME, obj.loadNoDelay, obj.loaded, require(obj.__CLASSNAME).loaded)
if delayloading and not obj.loadNoDelay then
engine.Savefile.current_save:addDelayLoad(obj)
else
obj:loaded()
end
end
end
return obj
end
--- "Reloads" a cloneFull result object
-- This will make sure each object and subobject method :loaded() is called
function _M:cloneReloaded()
local delay_load = {}
local seen = {}
local function reload(obj)
-- print("setting obj class", obj.__CLASSNAME)
setmetatable(obj, {__index=require(obj.__CLASSNAME)})
if obj.loaded then
-- print("loader found for class", obj, obj.__CLASSNAME)
if not obj.loadNoDelay then
delay_load[#delay_load+1] = obj
else
obj:loaded()
end
end
end
local function recurs(t)
if seen[t] then return end
seen[t] = true
for k, e in pairs(t) do
if type(k) == "table" then
recurs(k)
if k.__CLASSNAME then reload(k) end
end
if type(e) == "table" then
recurs(e)
if e.__CLASSNAME then reload(e) end
end
end
end
-- Start reloading
recurs(self)
reload(self)
-- Computed delayed loads
for i = 1, #delay_load do delay_load[i]:loaded() end
end
return _M
| gpl-3.0 |
madpilot78/ntopng | attic/scripts/lua/modules/recipients/recipients.lua | 2 | 2196 | --
-- (C) 2017-21 - ntop.org
--
local json = require "dkjson"
-- ##############################################
local recipients = {}
-- ##############################################
function recipients:create(args)
if args then
-- We're being sub-classed
if not args.key then
return nil
end
end
local this = args or {key = "base", enabled = true}
setmetatable(this, self)
self.__index = self
if args then
-- Initialization is only run if a subclass is being instanced, that is,
-- when args is not nil
this:_initialize()
end
return this
end
-- ##############################################
-- @brief Performs initialization operations at the time when the instance is created
function recipients:_initialize()
-- Possibly create a default recipient (if not existing)
end
-- ##############################################
-- @brief Dispatches a store `notification` to the recipient
-- @param notification A JSON string with all the alert information
-- @return true If the dispatching has been successfull, false otherwise
function recipients:dispatch_store_notification(notification)
return self.enabled
end
-- ##############################################
-- @brief Dispatches a trigger `notification` to the recipient
-- @param notification A JSON string with all the alert information
-- @return true If the dispatching has been successfull, false otherwise
function recipients:dispatch_trigger_notification(notification)
return self.enabled
end
-- ##############################################
-- @brief Dispatches a release `notification` to the recipient
-- @param notification A JSON string with all the alert information
-- @return true If the dispatching has been successfull, false otherwise
function recipients:dispatch_release_notification(notification)
return self.enabled
end
-- ##############################################
-- @brief Process notifications previously dispatched with one of the dispatch_{store,trigger,release}_notification
function recipients:process_notifications()
return self.enabled
end
-- ##############################################
return recipients
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/flame.lua | 2 | 2187 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
--------------------------------------------------------------------------------------
-- Advanced shaders
--------------------------------------------------------------------------------------
if core.shader.active(4) then
use_shader = {type="fireflash"}
base_size = 64
local nb = 0
return {
system_rotation = rng.range(0,359), system_rotationv = 0,
generator = function()
return {
life = 8,
size = 64, sizev = 0, sizea = 0,
x = 0, xv = 0, xa = 0,
y = 0, yv = 0, ya = 0,
dir = 0, dirv = dirv, dira = 0,
vel = 0, velv = 0, vela = 0,
r = 1, rv = 0, ra = 0,
g = 1, gv = 0, ga = 0,
b = 1, bv = 0, ba = 0,
a = 0.7, av = 0, aa = 0,
}
end, },
function(self)
if nb < 1 then
self.ps:emit(1)
end
nb = nb + 1
end,
1, "particles_images/fireflash"
--------------------------------------------------------------------------------------
-- Default
--------------------------------------------------------------------------------------
else
base_size = 32
return {
base = 1000,
angle = { 0, 360 }, anglev = { 2000, 4000 }, anglea = { 200, 600 },
life = { 5, 10 },
size = { 3, 6 }, sizev = {0, 0}, sizea = {0, 0},
r = {200, 255}, rv = {0, 0}, ra = {0, 0},
g = {120, 170}, gv = {0, 0}, ga = {0, 0},
b = {0, 0}, bv = {0, 0}, ba = {0, 0},
a = {255, 255}, av = {0, 0}, aa = {0, 0},
}, function(self)
self.nb = (self.nb or 0) + 1
if self.nb < 4 then
self.ps:emit(100)
end
end
end | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bhaflau_Remnants/Zone.lua | 1 | 1129 | -----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
knixeur/notion | ioncore/ioncore_luaext.lua | 2 | 1856 | --
-- ion/share/ioncore_luaext.lua
--
-- Copyright (c) Tuomo Valkonen 2004-2007.
--
-- See the included file LICENSE for details.
--
--DOC
-- Make \var{str} shell-safe.
function string.shell_safe(str)
return "'"..string.gsub(str, "'", "'\\''").."'"
end
--DOC
-- Make copy of \var{table}. If \var{deep} is unset, shallow one-level
-- copy is made, otherwise a deep copy is made.
function table.copy(t, deep)
local function docopy(t, deep, seen)
local nt={}
for k, v in pairs(t) do
local v2=v
if deep and type(v)=="table" then
if seen[v] then
error(TR("Recursive table - unable to deepcopy"))
end
seen[v]=true
v2=docopy(v, deep, seen)
seen[v]=nil
end
nt[k]=v2
end
return nt
end
return docopy(t, deep, deep and {})
end
--DOC
-- Add entries that do not exist in \var{t1} from \var{t2} to \var{t1}.
function table.append(t1, t2)
for k, v in pairs(t2) do
if t1[k]==nil then
t1[k]=v
end
end
return t1
end
--DOC
-- Create a table containing all entries from \var{t1} and those from
-- \var{t2} that are missing from \var{t1}.
function table.join(t1, t2)
return table.append(table.copy(t1, false), t2)
end
--DOC
-- Insert all positive integer entries from t2 into t1.
function table.icat(t1, t2)
for _, v in ipairs(t2) do
table.insert(t1, v)
end
return t1
end
--DOC
-- Map all entries of \var{t} by \var{f}.
function table.map(f, t)
local res={}
for k, v in pairs(t) do
res[k]=f(v)
end
return res
end
--DOC
-- Export a list of functions from \var{lib} into global namespace.
function export(lib, ...)
for k, v in pairs({...}) do
_G[v]=lib[v]
end
end
| lgpl-2.1 |
FihlaTV/C-RTMP-Server | configs/stresstest.lua | 15 | 1873 | -- Start of the configuration. This is the only node in the config file.
-- The rest of them are sub-nodes
configuration=
{
-- if true, the server will run as a daemon.
-- NOTE: all console appenders will be ignored if this is a daemon
daemon=false,
-- the OS's path separator. Used in composing paths
pathSeparator="/",
-- this is the place where all the logging facilities are setted up
-- you can add/remove any number of locations
logAppenders=
{
{
-- name of the appender. Not too important, but is mandatory
name="console appender",
-- type of the appender. We can have the following values:
-- console, coloredConsole and file
-- NOTE: console appenders will be ignored if we run the server
-- as a daemon
type="coloredConsole",
-- the level of logging. 6 is the FINEST message, 0 is FATAL message.
-- The appender will "catch" all the messages below or equal to this level
-- bigger the level, more messages are recorded
level=6
},
{
name="file appender",
type="file",
level=6,
-- the file where the log messages are going to land
fileName="/tmp/crtmpserver",
--newLineCharacters="\r\n",
fileHistorySize=10,
fileLength=1024*256,
singleLine=true
}
},
-- this node holds all the RTMP applications
applications=
{
-- this is the root directory of all applications
-- usually this is relative to the binary execuable
rootDirectory="applications",
{
name="stresstest",
description="Application for stressing a streaming server",
protocol="dynamiclinklibrary",
targetServer="localhost",
targetApp="vod",
active=true,
default=true,
streams =
{
--"mp4:lg.mp4","myStream","someOtherStream"
"test1"
},
numberOfConnections=1000,
randomAccessStreams=false
},
--#INSERTION_MARKER# DO NOT REMOVE THIS. USED BY appscaffold SCRIPT.
}
}
| gpl-3.0 |
Moodstocks/stnbhwd | demo/Optim.lua | 4 | 9436 | --[[ That would be the license for Optim.lua
BSD License
For fbcunn software
Copyright (c) 2014, Facebook, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Facebook nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
-- Copyright 2004-present Facebook. All Rights Reserved.
local pl = require('pl.import_into')()
-- from fblualib/fb/util/data.lua , copied here because fblualib is not rockspec ready yet.
-- deepcopy routine that assumes the presence of a 'clone' method in user
-- data should be used to deeply copy. This matches the behavior of Torch
-- tensors.
local function deepcopy(x)
local typename = type(x)
if typename == "userdata" then
return x:clone()
end
if typename == "table" then
local retval = { }
for k,v in pairs(x) do
retval[deepcopy(k)] = deepcopy(v)
end
return retval
end
return x
end
local Optim, parent = torch.class('nn.Optim')
-- Returns weight parameters and bias parameters and associated grad parameters
-- for this module. Annotates the return values with flag marking parameter set
-- as bias parameters set
function Optim.weight_bias_parameters(module)
local weight_params, bias_params
if module.weight then
weight_params = {module.weight, module.gradWeight}
weight_params.is_bias = false
end
if module.bias then
bias_params = {module.bias, module.gradBias}
bias_params.is_bias = true
end
return {weight_params, bias_params}
end
-- The regular `optim` package relies on `getParameters`, which is a
-- beastly abomination before all. This `optim` package uses separate
-- optim state for each submodule of a `nn.Module`.
function Optim:__init(model, optState, checkpoint_data)
assert(model)
assert(checkpoint_data or optState)
assert(not (checkpoint_data and optState))
self.model = model
self.modulesToOptState = {}
-- Keep this around so we update it in setParameters
self.originalOptState = optState
-- Each module has some set of parameters and grad parameters. Since
-- they may be allocated discontinuously, we need separate optState for
-- each parameter tensor. self.modulesToOptState maps each module to
-- a lua table of optState clones.
if not checkpoint_data then
self.model:for_each(function(module)
self.modulesToOptState[module] = { }
local params = self.weight_bias_parameters(module)
-- expects either an empty table or 2 element table, one for weights
-- and one for biases
assert(pl.tablex.size(params) == 0 or pl.tablex.size(params) == 2)
for i, _ in ipairs(params) do
self.modulesToOptState[module][i] = deepcopy(optState)
if params[i] and params[i].is_bias then
-- never regularize biases
self.modulesToOptState[module][i].weightDecay = 0.0
end
end
assert(module)
assert(self.modulesToOptState[module])
end)
else
local state = checkpoint_data.optim_state
local modules = {}
self.model:for_each(function(m) table.insert(modules, m) end)
assert(pl.tablex.compare_no_order(modules, pl.tablex.keys(state)))
self.modulesToOptState = state
end
end
function Optim:save()
return {
optim_state = self.modulesToOptState
}
end
local function _type_all(obj, t)
for k, v in pairs(obj) do
if type(v) == 'table' then
_type_all(v, t)
else
local tn = torch.typename(v)
if tn and tn:find('torch%..+Tensor') then
obj[k] = v:type(t)
end
end
end
end
function Optim:type(t)
self.model:for_each(function(module)
local state= self.modulesToOptState[module]
assert(state)
_type_all(state, t)
end)
end
local function get_device_for_module(mod)
local dev_id = nil
for name, val in pairs(mod) do
if torch.typename(val) == 'torch.CudaTensor' then
local this_dev = val:getDevice()
if this_dev ~= 0 then
-- _make sure the tensors are allocated consistently
assert(dev_id == nil or dev_id == this_dev)
dev_id = this_dev
end
end
end
return dev_id -- _may still be zero if none are allocated.
end
local function on_device_for_module(mod, f)
local this_dev = get_device_for_module(mod)
if this_dev ~= nil then
return cutorch.withDevice(this_dev, f)
end
return f()
end
function Optim:optimize(optimMethod, inputs, targets, criterion)
assert(optimMethod)
assert(inputs)
assert(targets)
assert(criterion)
assert(self.modulesToOptState)
self.model:zeroGradParameters()
local output = self.model:forward(inputs)
local err = criterion:forward(output, targets)
local df_do = criterion:backward(output, targets)
self.model:backward(inputs, df_do)
-- We'll set these in the loop that iterates over each module. Get them
-- out here to be captured.
local curGrad
local curParam
local function fEvalMod(x)
return err, curGrad
end
for curMod, opt in pairs(self.modulesToOptState) do
on_device_for_module(curMod, function()
local curModParams = self.weight_bias_parameters(curMod)
-- expects either an empty table or 2 element table, one for weights
-- and one for biases
assert(pl.tablex.size(curModParams) == 0 or
pl.tablex.size(curModParams) == 2)
if curModParams then
for i, tensor in ipairs(curModParams) do
if curModParams[i] then
-- expect param, gradParam pair
curParam, curGrad = table.unpack(curModParams[i])
assert(curParam and curGrad)
optimMethod(fEvalMod, curParam, opt[i])
end
end
end
end)
end
return err, output
end
function Optim:optimizeFromGradients(optimMethod, inputs, gradients)
assert(optimMethod)
assert(inputs)
assert(gradients)
assert(self.modulesToOptState)
self.model:zeroGradParameters()
self.model:backward(inputs, gradients)
-- We'll set these in the loop that iterates over each module. Get them
-- out here to be captured.
local curGrad
local curParam
local function fEvalMod(x)
return 0, curGrad
end
for curMod, opt in pairs(self.modulesToOptState) do
on_device_for_module(curMod, function()
local curModParams = self.weight_bias_parameters(curMod)
-- expects either an empty table or 2 element table, one for weights
-- and one for biases
assert(pl.tablex.size(curModParams) == 0 or
pl.tablex.size(curModParams) == 2)
if curModParams then
for i, tensor in ipairs(curModParams) do
if curModParams[i] then
-- expect param, gradParam pair
curParam, curGrad = table.unpack(curModParams[i])
assert(curParam and curGrad)
optimMethod(fEvalMod, curParam, opt[i])
end
end
end
end)
end
return err, output
end
function Optim:setParameters(newParams)
assert(newParams)
assert(type(newParams) == 'table')
local function splice(dest, src)
for k,v in pairs(src) do
dest[k] = v
end
end
splice(self.originalOptState, newParams)
for _,optStates in pairs(self.modulesToOptState) do
for i,optState in pairs(optStates) do
assert(type(optState) == 'table')
splice(optState, newParams)
end
end
end | mit |
RyMarq/Zero-K | units/empmissile.lua | 1 | 3035 | return { empmissile = {
unitname = [[empmissile]],
name = [[Shockley]],
description = [[EMP missile]],
buildCostMetal = 600,
builder = false,
buildPic = [[empmissile.png]],
category = [[SINK UNARMED]],
collisionVolumeOffsets = [[0 15 0]],
collisionVolumeScales = [[20 50 20]],
collisionVolumeType = [[CylY]],
customParams = {
mobilebuilding = [[1]],
},
explodeAs = [[EMP_WEAPON]],
footprintX = 1,
footprintZ = 1,
iconType = [[cruisemissilesmall]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 1000,
maxSlope = 18,
minCloakDistance = 150,
objectName = [[wep_empmissile.s3o]],
script = [[cruisemissile.lua]],
selfDestructAs = [[EMP_WEAPON]],
sfxtypes = {
explosiongenerators = {
[[custom:RAIDMUZZLE]]
},
},
sightDistance = 0,
useBuildingGroundDecal = false,
yardMap = [[o]],
weapons = {
{
def = [[EMP_WEAPON]],
badTargetCategory = [[SWIM LAND SHIP HOVER]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP SUB]],
},
},
weaponDefs = {
EMP_WEAPON = {
name = [[EMP Missile]],
areaOfEffect = 280,
avoidFriendly = false,
cegTag = [[bigemptrail]],
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customparams = {
burst = Shared.BURST_RELIABLE,
restrict_in_widgets = 1,
stats_hide_dps = 1, -- one use
stats_hide_reload = 1,
light_color = [[1.35 1.35 0.36]],
light_radius = 450,
},
damage = {
default = 30002.4,
},
edgeEffectiveness = 1,
explosionGenerator = [[custom:EMPMISSILE_EXPLOSION]],
fireStarter = 0,
flightTime = 20,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
model = [[wep_empmissile.s3o]],
paralyzer = true,
paralyzeTime = 45,
range = 3500,
reloadtime = 3,
smokeTrail = false,
soundHit = [[weapon/missile/emp_missile_hit]],
soundStart = [[weapon/missile/tacnuke_launch]],
tolerance = 4000,
tracks = false,
turnrate = 12000,
weaponAcceleration = 180,
weaponTimer = 5,
weaponType = [[StarburstLauncher]],
weaponVelocity = 1200,
},
},
featureDefs = {
},
} }
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/objects/egos/robe.lua | 2 | 17800 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local Stats = require "engine.interface.ActorStats"
local Talents = require "engine.interface.ActorTalents"
local DamageType = require "engine.DamageType"
--load("/data/general/objects/egos/charged-defensive.lua")
--load("/data/general/objects/egos/charged-utility.lua")
-- Resists and saves
newEntity{
power_source = {nature=true},
name = " of fire (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {fire=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.FIRE] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.FIRE] = (e.wielder.resists[engine.DamageType.FIRE] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.FIRE]*1.5) end),
}
newEntity{
power_source = {nature=true},
name = " of frost (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {frost=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.COLD] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.COLD] = (e.wielder.resists[engine.DamageType.COLD] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.COLD]*1.5) end),
}
newEntity{
power_source = {nature=true},
name = " of nature (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {nature=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.NATURE] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.NATURE] = (e.wielder.resists[engine.DamageType.NATURE] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.NATURE]*1.5) end),
}
newEntity{
power_source = {nature=true},
name = " of lightning (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {lightning=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.LIGHTNING] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.LIGHTNING] = (e.wielder.resists[engine.DamageType.LIGHTNING] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.LIGHTNING]*1.5) end),
}
newEntity{
power_source = {arcane=true},
name = " of light (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {light=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.LIGHT] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.LIGHT] = (e.wielder.resists[engine.DamageType.LIGHT] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.LIGHT]*1.5) end),
}
newEntity{
power_source = {arcane=true},
name = " of darkness (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {darkness=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.DARKNESS] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.DARKNESS] = (e.wielder.resists[engine.DamageType.DARKNESS] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.DARKNESS]*1.5) end),
}
newEntity{
power_source = {nature=true},
name = " of corrosion (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {corrosion=true},
level_range = {1, 50},
rarity = 6,
cost = 2,
wielder = {
inc_damage = { [DamageType.ACID] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.ACID] = (e.wielder.resists[engine.DamageType.ACID] or 0) + math.floor(e.wielder.inc_damage[engine.DamageType.ACID]*1.5) end),
}
-- rare resists
newEntity{
power_source = {arcane=true},
name = " of blight (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {blight=true},
level_range = {1, 50},
rarity = 9,
cost = 2,
wielder = {
inc_damage = { [DamageType.BLIGHT] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.BLIGHT] = (e.wielder.resists[engine.DamageType.BLIGHT] or 0) + (e.wielder.inc_damage[engine.DamageType.BLIGHT]) end),
}
newEntity{
power_source = {nature=true},
name = " of the mountain (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {mountain=true},
level_range = {1, 50},
rarity = 12,
cost = 2,
wielder = {
inc_damage = { [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.PHYSICAL] = (e.wielder.resists[engine.DamageType.PHYSICAL] or 0) + (e.wielder.inc_damage[engine.DamageType.PHYSICAL]) end),
}
newEntity{
power_source = {psionic=true},
name = " of the mind (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {mind=true},
level_range = {1, 50},
rarity = 9,
cost = 2,
wielder = {
inc_damage = { [DamageType.MIND] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.MIND] = (e.wielder.resists[engine.DamageType.MIND] or 0) + (e.wielder.inc_damage[engine.DamageType.MIND]) end),
}
newEntity{
power_source = {arcane=true},
name = " of time (#RESIST#)", suffix=true, instant_resolve=true,
keywords = {time=true},
level_range = {1, 50},
rarity = 12,
cost = 2,
wielder = {
inc_damage = { [DamageType.TEMPORAL] = resolvers.mbonus_material(10, 10) },
resists = {},
},
resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.TEMPORAL] = (e.wielder.resists[engine.DamageType.TEMPORAL] or 0) + (e.wielder.inc_damage[engine.DamageType.TEMPORAL]) end),
}
-- Arcane Damage doesn't get resist too so we give it +mana instead
newEntity{
power_source = {arcane=true},
name = "shimmering ", prefix=true, instant_resolve=true,
keywords = {shimmering=true},
level_range = {1, 50},
rarity = 12,
cost = 6,
wielder = {
inc_damage = { [DamageType.ARCANE] = resolvers.mbonus_material(10, 10) },
max_mana = resolvers.mbonus_material(100, 10),
},
}
-- Saving Throws (robes give good saves)
newEntity{
power_source = {technique=true},
name = " of protection", suffix=true, instant_resolve=true,
keywords = {prot=true},
level_range = {1, 50},
rarity = 7,
cost = 6,
wielder = {
combat_armor = resolvers.mbonus_material(3, 2),
combat_def = resolvers.mbonus_material(3, 2),
combat_physresist = resolvers.mbonus_material(15, 15),
},
}
newEntity{
power_source = {psionic=true},
name = "dreamer's ", prefix=true, instant_resolve=true,
keywords = {dreamer=true},
level_range = {20, 50},
greater_ego = 1,
rarity = 30,
cost = 60,
wielder = {
lucid_dreamer=1,
sleep=1,
resists={
[DamageType.MIND] = resolvers.mbonus_material(20, 10),
[DamageType.DARKNESS] = resolvers.mbonus_material(20, 10),
},
combat_physresist = resolvers.mbonus_material(10, 10),
combat_spellresist = resolvers.mbonus_material(10, 10),
combat_mentalresist = resolvers.mbonus_material(20, 20),
},
}
newEntity{
power_source = {arcane=true},
name = "dispeller's ", prefix=true, instant_resolve=true,
keywords = {dispeller=true},
level_range = {30, 50},
greater_ego = 1,
rarity = 30,
cost = 60,
wielder = {
resists={
[DamageType.FIRE] = resolvers.mbonus_material(6, 6),
[DamageType.COLD] = resolvers.mbonus_material(6, 6),
[DamageType.BLIGHT] = resolvers.mbonus_material(6, 6),
[DamageType.LIGHTNING] = resolvers.mbonus_material(6, 6),
[DamageType.DARKNESS] = resolvers.mbonus_material(6, 6),
[DamageType.LIGHT] = resolvers.mbonus_material(6, 6),
},
combat_physresist = resolvers.mbonus_material(10, 10),
combat_mentalresist = resolvers.mbonus_material(10, 10),
combat_spellresist = resolvers.mbonus_material(20, 20),
},
}
-- The rest
newEntity{
power_source = {arcane=true},
name = " of alchemy", suffix=true, instant_resolve=true,
keywords = {alchemy=true},
level_range = {20, 50},
greater_ego = 1,
rarity = 20,
cost = 40,
wielder = {
inc_damage = {
[DamageType.ACID] = resolvers.mbonus_material(10, 5),
[DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5),
[DamageType.FIRE] = resolvers.mbonus_material(10, 5),
[DamageType.COLD] = resolvers.mbonus_material(10, 5),
},
resists={
[DamageType.ACID] = resolvers.mbonus_material(10, 10),
[DamageType.PHYSICAL] = resolvers.mbonus_material(10, 10),
[DamageType.FIRE] = resolvers.mbonus_material(10, 10),
[DamageType.COLD] = resolvers.mbonus_material(10, 10),
},
talent_cd_reduction = {
[Talents.T_REFIT_GOLEM] = resolvers.mbonus_material(4, 2),
}
},
}
newEntity{
power_source = {arcane=true},
name = "spellwoven ", prefix=true, instant_resolve=true,
keywords = {spellwoven=true},
level_range = {1, 50},
rarity = 7,
cost = 6,
wielder = {
combat_spellresist = resolvers.mbonus_material(15, 15),
combat_spellpower = resolvers.mbonus_material(4, 2),
combat_spellcrit = resolvers.mbonus_material(4, 2),
},
}
newEntity{
power_source = {arcane=true},
name = " of Linaniil", suffix=true, instant_resolve=true,
keywords = {Linaniil=true},
level_range = {35, 50},
greater_ego = 1,
rarity = 25,
cost = 60,
wielder = {
combat_spellpower = resolvers.mbonus_material(15, 15),
combat_spellcrit = resolvers.mbonus_material(10, 5),
max_mana = resolvers.mbonus_material(60, 40),
mana_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end),
},
}
newEntity{
power_source = {arcane=true},
name = " of Angolwen", suffix=true, instant_resolve=true,
keywords = {Angolwen=true},
level_range = {35, 50},
greater_ego = 1,
rarity = 20,
cost = 60,
wielder = {
inc_stats = {
[Stats.STAT_MAG] = resolvers.mbonus_material(4, 2),
[Stats.STAT_WIL] = resolvers.mbonus_material(4, 2),
},
combat_spellpower = resolvers.mbonus_material(15, 5),
spellsurge_on_crit = resolvers.mbonus_material(5, 2),
silence_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end),
},
}
newEntity{
power_source = {arcane=true},
name = "stargazer's ", prefix=true, instant_resolve=true,
keywords = {stargazer=true},
level_range = {30, 50},
greater_ego = 1,
rarity = 15,
cost = 30,
wielder = {
inc_stats = {
[Stats.STAT_CUN] = resolvers.mbonus_material(5, 1),
},
inc_damage = {
[DamageType.LIGHT] = resolvers.mbonus_material(15, 5),
[DamageType.DARKNESS] = resolvers.mbonus_material(15, 5),
},
combat_spellpower = resolvers.mbonus_material(5, 5),
combat_spellcrit = resolvers.mbonus_material(5, 5),
},
}
newEntity{
power_source = {arcane=true},
name = "ancient ", prefix=true, instant_resolve=true,
keywords = {ancient=true},
level_range = {30, 50},
greater_ego = 1,
rarity = 40,
cost = 40,
wielder = {
inc_stats = {
[Stats.STAT_MAG] = resolvers.mbonus_material(9, 1),
},
inc_damage = {
[DamageType.TEMPORAL] = resolvers.mbonus_material(15, 5),
},
resists_pen = {
[DamageType.TEMPORAL] = resolvers.mbonus_material(10, 5),
},
resists = {
[DamageType.TEMPORAL] = resolvers.mbonus_material(10, 5),
},
paradox_reduce_anomalies = resolvers.mbonus_material(8, 8),
},
}
newEntity{
power_source = {arcane=true},
name = " of power", suffix=true, instant_resolve=true,
keywords = {power=true},
level_range = {20, 50},
greater_ego = 1,
rarity = 18,
cost = 15,
wielder = {
inc_damage = {
all = resolvers.mbonus_material(15, 5),
},
combat_spellpower = resolvers.mbonus_material(10, 10),
},
}
newEntity{
power_source = {arcane=true},
name = "sunsealed ", prefix=true, instant_resolve=true,
keywords = {sunseal=true},
level_range = {40, 50},
greater_ego = 1,
rarity = 30,
cost = 80,
wielder = {
resists={
[DamageType.LIGHT] = resolvers.mbonus_material(10, 5),
[DamageType.DARKNESS] = resolvers.mbonus_material(10, 5),
},
inc_damage = {
[DamageType.LIGHT] = resolvers.mbonus_material(15, 5),
},
inc_stats = {
[Stats.STAT_MAG] = resolvers.mbonus_material(7, 3),
},
combat_armor = resolvers.mbonus_material(5, 3),
combat_def = resolvers.mbonus_material(5, 3),
lite = resolvers.mbonus_material(3,1),
max_life=resolvers.mbonus_material(40, 30),
},
}
newEntity{
power_source = {nature=true},
name = " of life", suffix=true, instant_resolve=true,
keywords = {life=true},
level_range = {20, 50},
greater_ego = 1,
rarity = 20,
cost = 60,
wielder = {
max_life=resolvers.mbonus_material(60, 40),
life_regen = resolvers.mbonus_material(45, 15, function(e, v) v=v/10 return 0, v end),
healing_factor = resolvers.mbonus_material(20, 10, function(e, v) v=v/100 return 0, v end),
resists={
[DamageType.BLIGHT] = resolvers.mbonus_material(15, 5),
},
},
}
newEntity{
power_source = {antimagic=true},
name = "slimy ", prefix=true, instant_resolve=true,
keywords = {slimy=true},
level_range = {1, 50},
rarity = 7,
cost = 6,
wielder = {
on_melee_hit={
[DamageType.ITEM_NATURE_SLOW] = resolvers.mbonus_material(7, 3),
[DamageType.ITEM_ANTIMAGIC_MANABURN] = resolvers.mbonus_material(7, 3)
},
},
}
newEntity{
power_source = {nature=true},
name = "stormwoven ", prefix=true, instant_resolve=true,
keywords = {storm=true},
level_range = {30, 50},
greater_ego = 1,
rarity = 16,
cost = 50,
wielder = {
resists={
[DamageType.COLD] = resolvers.mbonus_material(10, 5),
[DamageType.LIGHTNING] = resolvers.mbonus_material(10, 5),
},
inc_stats = {
[Stats.STAT_STR] = resolvers.mbonus_material(4, 4),
[Stats.STAT_MAG] = resolvers.mbonus_material(4, 4),
[Stats.STAT_WIL] = resolvers.mbonus_material(4, 4),
},
inc_damage = {
[DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5),
[DamageType.COLD] = resolvers.mbonus_material(15, 5),
[DamageType.LIGHTNING] = resolvers.mbonus_material(15, 5),
},
},
}
newEntity{
power_source = {nature=true},
name = "verdant ", prefix=true, instant_resolve=true,
keywords = {verdant=true},
level_range = {20, 50},
greater_ego = 1,
rarity = 15,
cost = 30,
wielder = {
inc_stats = {
[Stats.STAT_CON] = resolvers.mbonus_material(8, 2),
},
inc_damage = {
[DamageType.NATURE] = resolvers.mbonus_material(15, 5),
},
disease_immune = resolvers.mbonus_material(30, 20, function(e, v) return 0, v/100 end),
poison_immune = resolvers.mbonus_material(30, 20, function(e, v) return 0, v/100 end),
},
}
newEntity{
power_source = {psionic=true},
name = "mindwoven ", prefix=true, instant_resolve=true,
keywords = {mindwoven=true},
level_range = {1, 50},
rarity = 7,
cost = 6,
wielder = {
combat_mentalresist = resolvers.mbonus_material(15, 15),
combat_mindpower = resolvers.mbonus_material(4, 2),
combat_mindcrit = resolvers.mbonus_material(4, 2),
},
}
newEntity{
power_source = {psionic=true},
name = "tormentor's ", prefix=true, instant_resolve=true,
keywords = {tormentor=true},
level_range = {30, 50},
greater_ego = 1,
rarity = 30,
cost = 60,
wielder = {
inc_stats = {
[Stats.STAT_CUN] = resolvers.mbonus_material(9, 1),
},
combat_critical_power = resolvers.mbonus_material(10, 10),
hate_on_crit = resolvers.mbonus_material(3, 2),
psi_on_crit = resolvers.mbonus_material(4, 1),
},
}
newEntity{
power_source = {psionic=true},
name = "focusing ", prefix=true, instant_resolve=true,
keywords = {focus=true},
level_range = {15, 50},
rarity = 10,
cost = 10,
wielder = {
inc_stats = {
[Stats.STAT_MAG] = resolvers.mbonus_material(4, 4),
[Stats.STAT_WIL] = resolvers.mbonus_material(4, 4),
},
mana_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end),
psi_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end),
},
}
newEntity{
power_source = {psionic=true},
name = "fearwoven ", prefix=true, instant_resolve=true,
keywords = {fearwoven=true},
level_range = {40, 50},
greater_ego = 1,
rarity = 40,
cost = 80,
wielder = {
inc_damage = {
[DamageType.PHYSICAL] = resolvers.mbonus_material(15, 5),
[DamageType.DARKNESS] = resolvers.mbonus_material(15, 5),
},
resists_pen = {
[DamageType.PHYSICAL] = resolvers.mbonus_material(15, 5),
[DamageType.DARKNESS] = resolvers.mbonus_material(15, 5),
},
max_hate = resolvers.mbonus_material(10, 5),
combat_mindpower = resolvers.mbonus_material(5, 5),
combat_mindcrit = resolvers.mbonus_material(4, 1),
},
}
newEntity{
power_source = {psionic=true},
name = "psion's ", prefix=true, instant_resolve=true,
keywords = {psion=true},
level_range = {40, 50},
greater_ego = 1,
rarity = 40,
cost = 80,
wielder = {
inc_damage = {
[DamageType.MIND] = resolvers.mbonus_material(15, 5),
},
resists_pen = {
[DamageType.MIND] = resolvers.mbonus_material(15, 5),
},
max_psi = resolvers.mbonus_material(30, 10),
psi_regen = resolvers.mbonus_material(70, 30, function(e, v) v=v/100 return 0, v end),
combat_mindpower = resolvers.mbonus_material(5, 5),
combat_mindcrit = resolvers.mbonus_material(4, 1),
},
} | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Dynamis-Valkurm/Zone.lua | 1 | 1126 | -----------------------------------
--
-- Zone: Dynamis-Valkurm
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil;
require("scripts/zones/Dynamis-Valkurm/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_heavy_gtm_4.meta.lua | 2 | 2850 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -7,
y = -10
},
rotation = 45
},
head = {
pos = {
x = 2,
y = -1
},
rotation = 18.799886703491211
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 9,
y = 28
},
rotation = -24.863697052001953
},
secondary_hand = {
pos = {
x = 42,
y = 11
},
rotation = 82.405357360839844
},
secondary_shoulder = {
pos = {
x = -1,
y = 18
},
rotation = -164
},
shoulder = {
pos = {
x = 20,
y = -10
},
rotation = -120.06858062744141
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/zones/town-iron-council/grids.lua | 3 | 3299 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
load("/data/general/grids/basic.lua")
load("/data/general/grids/underground.lua")
for i = 1, 20 do
newEntity{
define_as = "CRYSTAL_WALL"..(i > 1 and i or ""),
type = "wall", subtype = "underground",
name = "crystals",
image = "terrain/oldstone_floor.png",
add_displays = class:makeCrystals("terrain/crystal_alpha"),
display = '#', color=colors.LIGHT_BLUE, back_color=colors.UMBER,
always_remember = true,
can_pass = {pass_wall=1},
does_block_move = true,
block_sight = true,
dig = "CRYSTAL_FLOOR",
}
end
newEntity{ base = "DOWN", define_as = "ESCAPE_REKNOR", name="Escape route from Reknor", change_zone="reknor-escape", change_level=3, change_zone_auto_stairs = true }
newEntity{ base = "DOWN", define_as = "DEEP_BELLOW", name="The Deep Bellow", glow=true, change_zone="deep-bellow" }
newEntity{ define_as = "STATUE1",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_taxman.png", z=18, display_y=-1, display_h=2}},
name = "The Dwarven Empire Incarnate",
does_block_move = true,
block_sight = true,
}
newEntity{ define_as = "STATUE2",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_mage.png", z=18, display_y=-1, display_h=2}},
name = "Mystic of the Empire",
does_block_move = true,
block_sight = true,
}
newEntity{ define_as = "STATUE3",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_axeman.png", z=18, display_y=-1, display_h=2}},
name = "Warrior of the Empire",
does_block_move = true,
block_sight = true,
}
newEntity{ define_as = "STATUE4",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_warrior.png", z=18, display_y=-1, display_h=2}},
name = "Defender of the Empire",
does_block_move = true,
block_sight = true,
}
newEntity{ define_as = "STATUE5",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_axeman2.png", z=18, display_y=-1, display_h=2}},
name = "Warrior of the Empire",
does_block_move = true,
block_sight = true,
}
newEntity{ define_as = "STATUE6",
display = '@', image="terrain/oldstone_floor.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_dwarf_archer.png", z=18, display_y=-1, display_h=2}},
name = "Warrior of the Empire",
does_block_move = true,
block_sight = true,
}
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Waters/npcs/Sohdede.lua | 5 | 1040 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Sohdede
-- Type: Standard NPC
-- @zone: 238
-- @pos: -60.601 -7.499 111.639
--
-- 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(0x0176);
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 |
notcake/cac-administration | ulxsourcebansbansystem.lua | 1 | 1117 | local self = {}
CAC.ULXSourceBansBanSystem = CAC.MakeConstructor (self, CAC.BanSystem)
function self:ctor ()
end
-- IReadOnlyBanSystem
function self:GetId ()
return "ULXSourceBansBanSystem"
end
function self:GetName ()
return "ULX SourceBans"
end
function self:IsAvailable ()
return istable (SBAN)
end
-- IBanSystem
function self:Ban (userId, duration, reason, bannerId)
if duration == math.huge then duration = 0 end
local banner = CAC.PlayerMonitor:GetUserEntity (bannerId) or NULL
if not banner:IsValid () then
banner =
{
IsValid = function () return false end,
SteamID = function () return "Server" end
}
end
local SBAN_Admin_GetID = SBAN.Admin_GetID
SBAN.Admin_GetID = function (steamId, callback)
callback (0)
end
xpcall (ulx.sbanid,
function (message)
ErrorNoHalt (tostring (message) .. "\n" .. debug.traceback () .. "\n")
end,
banner, userId, duration / 60, reason
)
SBAN.Admin_GetID = SBAN_Admin_GetID or SBAN.Admin_GetID
end
function self:CanBanOfflineUsers ()
return true
end
CAC.SystemRegistry:RegisterSystem ("BanSystem", CAC.ULXSourceBansBanSystem ()) | mit |
fegimanam/best | plugins/autoleave.lua | 16 | 1845 | --[[
Kicking ourself (bot) from unmanaged groups.
When someone invited this bot to a group, the bot then will chek if the group
is in its moderations (moderation.json).
If not, the bot will exit immediately by kicking itself out of that group.
Enable plugin using !plugins plugin. And if your bot already invited into groups,
use following command to exit from those group;
!leave to leaving from current group.
!leaveall to exit from all unmanaged groups.
--]]
do
--Callbacks for get_dialog_list
local function cb_getdialog(extra, success, result)
local data = load_data(_config.moderation.data)
for k,v in pairs(result) do
if v.peer.id and v.peer.title then
if not data[tostring(v.peer.id)] then
chat_del_user("chat#id"..v.peer.id, 'user#id'..our_id, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if is_admin(msg.from.id, msg.to.id) then
if matches[1] == 'leave' then
chat_del_user("chat#id"..msg.to.id, 'user#id'..our_id, ok_cb, false)
elseif matches[1] == 'leaveall' then
get_dialog_list(cb_getdialog, {chat_id=msg.to.id})
end
end
if msg.action and msg.action.type == 'chat_add_user' and not is_sudo(msg.from.id) then
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
print '>>> autoleave: This is not our group. Leaving...'
chat_del_user('chat#id'..msg.to.id, 'user#id'..our_id, ok_cb, false)
end
end
end
return {
description = 'Exit from unmanaged groups.',
usage = {
admin = {
' ^!leave : Exit from this group.',
' ^!leaveall : Exit from all unmanaged groups.'
},
},
patterns = {
'^!(leave)$',
'^!(leaveall)$',
'^!!tgservice (chat_add_user)$'
},
run = run
}
end
| gpl-2.0 |
padrinoo1/teleunity | plugins/inrealm.lua | 287 | 25005 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Northern_San_dOria/npcs/Maurine.lua | 5 | 1024 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Maurine
-- Type: Standard Dialogue NPC
-- @zone: 231
-- @pos: 144.852 0.000 136.828
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MAURINE_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/zones/gladium/zone.lua | 3 | 1158 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return {
name = "Fortress Gladium",
level_range = {1, 1},
level_scheme = "player",
max_level = 1,
actor_adjust_level = function(zone, level, e) return zone.base_level end,
width = 15, height = 15,
all_remembered = true,
all_lited = true,
no_level_connectivity = true,
generator = {
map = {
class = "engine.generator.map.Static",
map = "zones/gladium",
},
},
}
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/tutorial/stats-tier/tier6.lua | 3 | 1425 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return [[
These new effects are #GOLD#cross-tier effects#WHITE#. They occur when a talent calls for comparing #GOLD#combat stats#WHITE# that aren't in the same tier.
Physical effects cause the "Off-balance" effect.
Magic effects cause the "Spellshocked" effect.
Mental effects cause the "Brainlocked" effect.
The effects last one turn per tier difference in the attacker's and defender's #GOLD#combat stats#WHITE#. For example, casting Mana Gale with a #8d55ff#Tier 5#WHITE# #LIGHT_GREEN#Spellpower#WHITE# on a target with a #B4B4B4#Tier 1#WHITE# #LIGHT_GREEN#Physical save#WHITE# would result in applying a four-turn "Off-balance" effect.
]]
| gpl-3.0 |
james2doyle/lit | libs/get-installed.lua | 3 | 1582 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local pathJoin = require('luvi').path.join
local pkgQuery = require('pkg').query
return function (fs, rootPath)
local deps = {}
local function check(dir)
local iter = fs.scandir(dir)
if not iter then return end
for entry in iter do
local baseName
if not entry.type then
local stat, err = fs.stat(pathJoin(dir, entry.name))
entry.type = stat and stat.type
end
if entry.type == "file" then
baseName = entry.name:match("^(.*)%.lua$")
elseif entry.type == "directory" then
baseName = entry.name
end
if baseName then
local path, meta
path = pathJoin(dir, entry.name)
meta, path = pkgQuery(fs, path)
if meta then
meta.fs = fs
meta.path = path
meta.location = dir:match("[^/]+$")
deps[baseName] = meta
end
end
end
end
check(pathJoin(rootPath, "deps"))
check(pathJoin(rootPath, "libs"))
return deps
end
| apache-2.0 |
SammyJames/LootDrop | Libs/LibAddonMenu-2.0/controls/header.lua | 2 | 1617 | --[[headerData = {
type = "header",
name = "My Header",
width = "full", --or "half" (optional)
reference = "MyAddonHeader" --(optional) unique global reference to control
} ]]
local widgetVersion = 4
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("header", widgetVersion) then return end
local wm = WINDOW_MANAGER
local tinsert = table.insert
local function UpdateValue(control)
control.header:SetText(control.data.name)
end
function LAMCreateControl.header(parent, headerData, controlName)
local control = wm:CreateTopLevelWindow(controlName or headerData.reference)
control:SetParent(parent.scroll or parent)
local isHalfWidth = headerData.width == "half"
control:SetDimensions(isHalfWidth and 250 or 510, 30)
control.divider = wm:CreateControlFromVirtual(nil, control, "ZO_Options_Divider")
local divider = control.divider
divider:SetWidth(isHalfWidth and 250 or 510)
divider:SetAnchor(TOPLEFT)
control.header = wm:CreateControlFromVirtual(nil, control, "ZO_Options_SectionTitleLabel")
local header = control.header
header:SetAnchor(TOPLEFT, divider, BOTTOMLEFT)
header:SetAnchor(BOTTOMRIGHT)
header:SetText(headerData.name)
control.panel = parent.panel or parent --if this is in a submenu, panel is its parent
control.data = headerData
control.UpdateValue = UpdateValue
if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list
tinsert(control.panel.controlsToRefresh, control)
end
return control
end | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.