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
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Ciqala.lua
22
1769
----------------------------------- -- Area: Bastok Markets -- NPC: Ciqala -- Type: Merchant -- @zone: 235 -- @pos -283.147 -11.319 -143.680 -- -- Auto-Script: Requires Verification -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, CIQALA_SHOP_DIALOG); stock = { 0x4006, 224,3, --Bronze Knuckles 0x4007, 828,3, --Brass Knuckles 0x4001, 129,3, --Cesti 0x4294, 1521,3, --Brass Baghnakhs 0x4015, 104,3, --Cat Baghnakhs 0x4292, 312,3, --Bronze Hammer 0x4293, 312,3, --Brass Hammer 0x4299, 47,3, --Maple Wand 0x4280, 66,3, --Ash Club 0x42A3, 90,3, --Bronze Rod 0x42B9, 621,3, --Brass Rod 0x42C0, 57,3, --Ash Staff 0x42C7, 386,3 --Ash Pole } showNationShop(player, BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
crabman77/minetest-minetestforfun-server
mods/homedecor_modpack/computer/computers.lua
11
10194
-- Amiga 500 lookalike computer.register("computer:shefriendSOO", { description = "SheFriendSOO", tiles_off = { front=true }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 0, 0, 17, 32, 32, 12 }, -- Monitor Screen { 3, 3, 29, 26, 26, 3 }, -- Monitor Tube { 0, 0, 0, 32, 4, 17 } -- Keyboard }) }) -- Some generic laptop minetest.register_node("computer:vanio", { drawtype = "mesh", mesh = "computer_laptop.obj", description = "Pony Vanio", inventory_image = "computer_laptop_inv.png", tiles = {"computer_laptop.png"}, paramtype = "light", paramtype2 = "facedir", light_source = 4, groups = {snappy=3}, walkable = false, selection_box = { type = "fixed", fixed = {-0.35, -0.5, -0.35, 0.35, 0.05, 0.35}, }, on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:vanio_off" minetest.set_node(pos, node) end }) minetest.register_node("computer:vanio_off", { drawtype = "mesh", mesh = "computer_laptop_closed.obj", tiles = {"computer_laptop.png"}, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, not_in_creative_inventory=1}, walkable = false, selection_box = { type = "fixed", fixed = {-0.35, -0.5, -0.35, 0.35, -0.4, 0.25}, }, drop = "computer:vanio", on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:vanio" minetest.set_node(pos, node) end }) -- Sony PlayStation lookalike computer.register("computer:slaystation", { description = "Pony SlayStation", inventory_image = "computer_ps1_inv.png", tiles_off = { top=true }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 0, 0, 11, 32, 6, 21 }, -- Console { 1, 0, 1, 4, 2, 9 }, -- Controller 1 L Grip { 10, 0, 1, 4, 2, 9 }, -- Controller 1 R Grip { 5, 0, 4, 5, 2, 5 }, -- Controller 1 Center { 18, 0, 1, 4, 2, 9 }, -- Controller 2 L Grip { 27, 0, 1, 4, 2, 9 }, -- Controller 2 R Grip { 22, 0, 4, 5, 2, 5 } -- Controller 2 Center }) }) -- Sony PlayStation 2 lookalike computer.register("computer:slaystation2", { description = "Pony SlayStation 2", inventory_image = "computer_ps2_inv.png", tiles_off = { front=true }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 2, 2, 11, 28, 3, 19 }, -- Console (Upper part) { 2, 0, 11, 26, 2, 19 }, -- Console (Lower part) { 1, 0, 1, 4, 2, 9 }, -- Controller 1 L Grip { 10, 0, 1, 4, 2, 9 }, -- Controller 1 R Grip { 5, 0, 1, 5, 2, 8 }, -- Controller 1 Center { 18, 0, 1, 4, 2, 9 }, -- Controller 2 L Grip { 27, 0, 1, 4, 2, 9 }, -- Controller 2 R Grip { 22, 0, 1, 5, 2, 8 } -- Controller 2 Center }) }) -- Sinclair ZX Spectrum lookalike computer.register("computer:specter", { description = "SX Specter", inventory_image = "computer_specter_inv.png", tiles_off = { }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 3, 0, 0, 26, 4, 17 }, -- Keyboard { 18, 0, 18, 12, 6, 14 } -- Tape Player }) }) -- Nintendo Wii lookalike computer.register("computer:wee", { description = "Nientiendo Wee", inventory_image = "computer_wii_inv.png", tiles_off = { front=true }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 11, 0, 3, 10, 6, 26 }, -- Base { 12, 6, 4, 8, 22, 24 } -- Top }) }) -- Apple iPad lookalike minetest.register_node("computer:piepad", { description = "Snapple Piepad", drawtype = "signlike", tiles = {"computer_piepad_inv.png"}, inventory_image = "computer_piepad_inv.png", wield_image = "computer_piepad_inv.png", paramtype = "light", paramtype2 = "wallmounted", light_source = 8, walkable = false, groups = {oddly_breakable_by_hand=2}, selection_box = {type = "wallmounted"}, sounds = default.node_sound_wood_defaults() }) -- Commodore 64 lookalike computer.register("computer:admiral64", { description = "Admiral64", inventory_image = "computer_ad64_inv.png", tiles_off = { }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 0, 0, 0, 32, 4, 18 } -- Keyboard }) }) -- Commodore 128 lookalike computer.register("computer:admiral128", { description = "Admiral128", inventory_image = "computer_ad128_inv.png", tiles_off = { }, node_box = computer.pixelnodebox(32, { -- X Y Z W H L { 0, 0, 0, 32, 4, 27 } -- Keyboard }) }) -- Generic Flat Screen LCD (16x9) with keyboard local mo_sbox = { type = "fixed", fixed = { -0.5, -0.5, -0.43, 0.5, 0.2, 0.25 } } minetest.register_node("computer:monitor", { description = "Monitor and keyboard", inventory_image = "computer_monitor_inv.png", drawtype = "mesh", mesh = "computer_monitor.obj", tiles = {"computer_black.png", "monitor_plastic.png", "computer_black.png", "monitor_plastic.png"}, paramtype = "light", paramtype2 = "facedir", walkable = false, groups = {snappy=3}, selection_box = mo_sbox, on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:monitor_on" minetest.set_node(pos, node) end }) minetest.register_node("computer:monitor_on", { description = "Monitor and keyboard", drawtype = "mesh", mesh = "computer_monitor.obj", tiles = {"monitor_display.png^[transformFX", "monitor_plastic.png", "computer_black.png", "monitor_plastic.png"}, paramtype = "light", paramtype2 = "facedir", light_source = 9, walkable = false, groups = {snappy=3, not_in_creative_inventory=1}, selection_box = mo_sbox, drop = "computer:monitor", on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:monitor" minetest.set_node(pos, node) end }) minetest.register_alias("computer:monitor_bios", "computer:monitor") minetest.register_alias("computer:monitor_loading", "computer:monitor") minetest.register_alias("computer:monitor_login", "computer:monitor") minetest.register_alias("computer:monitor_desktop", "computer:monitor") --WIFI Router (linksys look-a-like) minetest.register_node("computer:router", { description = "WIFI Router", inventory_image = "computer_router_inv.png", tiles = {"computer_router_t.png","computer_router_bt.png","computer_router_l.png","computer_router_r.png","computer_router_b.png", {name="computer_router_f_animated.png", animation={type="vertical_frames", aspect_w=32, aspect_h=32, length=1.0}},}, --"computer_router_f.png"}, paramtype = "light", paramtype2 = "facedir", walkable = false, groups = {snappy=3}, sound = default.node_sound_wood_defaults(), drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-0.25, -0.5, -0.0625, 0.25, -0.375, 0.3125}, {-0.1875, -0.4375, 0.3125, -0.125, -0.1875, 0.375}, {0.125, -0.4375, 0.3125, 0.1875, -0.1875, 0.375}, {-0.0625, -0.4375, 0.3125, 0.0625, -0.25, 0.375} } } }) local pct_cbox = { type = "fixed", fixed = { -0.1875, -0.5, -0.36, 0.1875, 0.34, 0.46 } } --Modern PC Tower minetest.register_node("computer:tower", { description = "Computer Tower", inventory_image = "computer_tower_inv.png", drawtype = "mesh", mesh = "computer_tower.obj", tiles = {"computer_tower.png"}, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3}, sound = default.node_sound_wood_defaults(), selection_box = pct_cbox, collision_box = pct_cbox }) minetest.register_alias("computer:tower_on", "computer:tower") -- Printer/scaner combo minetest.register_node("computer:printer", { description = "Printer Scaner Combo", inventory_image = "computer_printer_inv.png", tiles = {"computer_printer_t.png","computer_printer_bt.png","computer_printer_l.png", "computer_printer_r.png","computer_printer_b.png","computer_printer_f.png"}, paramtype = "light", paramtype2 = "facedir", walkable = true, groups = {snappy=3}, sound = default.node_sound_wood_defaults(), drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-0.4375, -0.3125, -0.125, 0.4375, -0.0625, 0.375}, {-0.4375, -0.5, -0.125, 0.4375, -0.4375, 0.375}, {-0.4375, -0.5, -0.125, -0.25, -0.0625, 0.375}, {0.25, -0.5, -0.125, 0.4375, -0.0625, 0.375}, {-0.4375, -0.5, -0.0625, 0.4375, -0.0625, 0.375}, {-0.375, -0.4375, 0.25, 0.375, -0.0625, 0.4375}, {-0.25, -0.25, 0.4375, 0.25, 0.0625, 0.5}, {-0.25, -0.481132, -0.3125, 0.25, -0.4375, 0} }, }, }) --Rack Server minetest.register_node("computer:server", { drawtype = "nodebox", description = "Rack Server", tiles = { 'computer_server_t.png', 'computer_server_bt.png', 'computer_server_l.png', 'computer_server_r.png', 'computer_server_bt.png', 'computer_server_f_off.png' }, inventory_image = "computer_server_inv.png", paramtype = "light", paramtype2 = "facedir", groups = {snappy=3}, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.25, 0.5, 1.125, 0.4375} }, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.25, 0.5, 1.125, 0.4375} }, sounds = default.node_sound_wood_defaults(), on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:server_on" minetest.set_node(pos, node) end, on_place = function(itemstack, placer, pointed_thing) local pos = pointed_thing.above if minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name ~= "air" then minetest.chat_send_player( placer:get_player_name(), "Not enough vertical space to place a server!" ) return end return minetest.item_place(itemstack, placer, pointed_thing) end }) minetest.register_node("computer:server_on", { drawtype = "nodebox", description = "Rack Server", tiles = { 'computer_server_t.png', 'computer_server_bt.png', 'computer_server_r.png', 'computer_server_l.png', 'computer_server_bt.png', 'computer_server_f_on.png', }, inventory_image = "computer_server_inv.png", paramtype = "light", paramtype2 = "facedir", groups = {snappy=3,not_in_creative_inventory=1}, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.25, 0.5, 1.125, 0.4375} }, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.25, 0.5, 1.125, 0.4375} }, sounds = default.node_sound_wood_defaults(), drop = 'computer:server', on_rightclick = function(pos, node, clicker, itemstack) node.name = "computer:server" minetest.set_node(pos, node) end })
unlicense
kitala1/darkstar
scripts/zones/Morimar_Basalt_Fields/npcs/HomePoint#1.lua
12
1221
----------------------------------- -- Area: Morimar Basalt Fields -- NPC: HomePoint#1 -- @pos -415 -63.2 409 265 ----------------------------------- package.loaded["scripts/zones/Morimar_Basalt_Fields/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Morimar_Basalt_Fields/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 48); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/wild_onion.lua
35
1193
----------------------------------------- -- ID: 4387 -- Item: wild_onion -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 4 -- Vitality -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4387); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, -6); end;
gpl-3.0
hwsyy/Atlas
examples/tutorial-query-time.lua
40
1786
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] --- -- getting the query time -- -- each injected query we send to the server has a start and end-time -- -- * start-time: when we call proxy.queries:append() -- * end-time: when we received the full result-set -- -- @param packet the mysql-packet sent by the client -- -- @return -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- function read_query( packet ) if packet:byte() == proxy.COM_QUERY then print("we got a normal query: " .. packet:sub(2)) proxy.queries:append(1, packet, { resultset_is_needed = false} ) return proxy.PROXY_SEND_QUERY end end --- -- read_query_result() is called when we receive a query result -- from the server -- -- inj.query_time is the query-time in micro-seconds -- -- @return -- * nothing or proxy.PROXY_SEND_RESULT to pass the result-set to the client -- function read_query_result(inj) print("query-time: " .. (inj.query_time / 1000) .. "ms") print("response-time: " .. (inj.response_time / 1000) .. "ms") end
gpl-2.0
fastmailops/prosody
util/template.lua
6
2836
local stanza_mt = require "util.stanza".stanza_mt; local setmetatable = setmetatable; local pairs = pairs; local ipairs = ipairs; local error = error; local loadstring = loadstring; local debug = debug; local t_remove = table.remove; local parse_xml = require "util.xml".parse; module("template") local function trim_xml(stanza) for i=#stanza,1,-1 do local child = stanza[i]; if child.name then trim_xml(child); else child = child:gsub("^%s*", ""):gsub("%s*$", ""); stanza[i] = child; if child == "" then t_remove(stanza, i); end end end end local function create_string_string(str) str = ("%q"):format(str); str = str:gsub("{([^}]*)}", function(s) return '"..(data["'..s..'"]or"").."'; end); return str; end local function create_attr_string(attr, xmlns) local str = '{'; for name,value in pairs(attr) do if name ~= "xmlns" or value ~= xmlns then str = str..("[%q]=%s;"):format(name, create_string_string(value)); end end return str..'}'; end local function create_clone_string(stanza, lookup, xmlns) if not lookup[stanza] then local s = ('setmetatable({name=%q,attr=%s,tags={'):format(stanza.name, create_attr_string(stanza.attr, xmlns)); -- add tags for i,tag in ipairs(stanza.tags) do s = s..create_clone_string(tag, lookup, stanza.attr.xmlns)..";"; end s = s..'};'; -- add children for i,child in ipairs(stanza) do if child.name then s = s..create_clone_string(child, lookup, stanza.attr.xmlns)..";"; else s = s..create_string_string(child)..";" end end s = s..'}, stanza_mt)'; s = s:gsub('%.%.""', ""):gsub('([=;])""%.%.', "%1"):gsub(';"";', ";"); -- strip empty strings local n = #lookup + 1; lookup[n] = s; lookup[stanza] = "_"..n; end return lookup[stanza]; end local function create_cloner(stanza, chunkname) local lookup = {}; local name = create_clone_string(stanza, lookup, ""); local f = "local setmetatable,stanza_mt=...;return function(data)"; for i=1,#lookup do f = f.."local _"..i.."="..lookup[i]..";"; end f = f.."return "..name..";end"; local f,err = loadstring(f, chunkname); if not f then error(err); end return f(setmetatable, stanza_mt); end local template_mt = { __tostring = function(t) return t.name end }; local function create_template(templates, text) local stanza, err = parse_xml(text); if not stanza then error(err); end trim_xml(stanza); local info = debug.getinfo(3, "Sl"); info = info and ("template(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.currentline) or "template(unknown)"; local template = setmetatable({ apply = create_cloner(stanza, info), name = info, text = text }, template_mt); templates[text] = template; return template; end local templates = setmetatable({}, { __mode = 'k', __index = create_template }); return function(text) return templates[text]; end;
mit
Pulse-Eight/drivers
Control4/tv_sink_pulse-eight/lib/c4_log.lua
9
17977
--[[============================================================================= c4_log Class Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.p8declares" require "lib.c4_object" c4_log = inheritsFrom(nil) function c4_log:construct(logName) self._logLevel = tonumber(string.sub(Properties['Log Level'] or "", 1, 1)) or 5 self._outputPrint = Properties['Log Mode']:find("Print") ~= nil self._outputC4Log = Properties['Log Mode']:find("Log") ~= nil self._logName = logName or "" -- make sure Property is up to date (no harm if absent) C4:UpdateProperty("Log Level", Properties['Log Level']) end function c4_log:SetLogLevel(level) self._logLevel = tonumber(string.sub(level or "", 1, 1)) or self._logLevel end function c4_log:LogLevel() return self._logLevel end function c4_log:OutputPrint(value) self._outputPrint = value end function c4_log:OutputC4Log(value) self._outputC4Log = value end function c4_log:SetLogName(logName) if (logName == nil or logName == "") then logName = "" else logName = logName .. ": " end self._logName = logName end function c4_log:LogName() return self._logName end function c4_log:Enabled() return (self._outputPrint or self._outputC4Log) end function c4_log:PrintEnabled() return self._outputPrint end function c4_log:C4LogEnabled() return self._outputC4Log end function c4_log:CreateTableText(tValue, tableText) tableText = tableText or "" if (type(tValue) == "table") then tableText = tableText .. "{" for k, v in pairs(tValue) do -- add key if (type(k) == "number") then tableText = tableText .. "[" .. tostring(k) .. "]=" elseif (type(k) == "string") then tableText = tableText .. k .. "=" else print (tostring(k) .. ": " .. tostring (v)) end -- add value if (type(v) == "number") then tableText = tableText .. tostring(v) .. "," elseif (type(v) == "string") then tableText = tableText .. "'" .. v .. "'," elseif (type(v) == "table") then tableText = c4_log:CreateTableText(v, tableText) tableText = tableText .. "," elseif (type(v) == "boolean") then tableText = tableText .. tostring(v) .. "," end end tableText = tableText .. "}" end return tableText end function InsertIndent(indentLevel) local indentStr = "" for i=1, indentLevel do indentStr = indentStr .. "\t" end return indentStr end function c4_log:CreateTableTextFormatted(tValue, tableText, indentLevel) tableText = tableText or "" indentLevel = indentLevel or 0 if (type(tValue) == "table") then indentLevel = indentLevel + 1 tableText = tableText .. "{\n" for k, v in pairs(tValue) do -- add key if (type(k) == "number") then tableText = tableText .. InsertIndent(indentLevel) .. "[" .. tostring(k) .. "]=" elseif (type(k) == "string") then tableText = tableText .. InsertIndent(indentLevel) .. k .. "=" else print (tostring(k) .. ": " .. tostring (v)) end -- add value if (type(v) == "number") then tableText = tableText .. tostring(v) .. ",\n" elseif (type(v) == "string") then tableText = tableText .. "'" .. v .. "',\n" elseif (type(v) == "table") then tableText = c4_log:CreateTableTextFormatted(v, tableText, indentLevel) tableText = tableText .. ",\n" elseif (type(v) == "boolean") then tableText = tableText .. tostring(v) .. ",\n" end end indentLevel = indentLevel - 1 tableText = tableText .. InsertIndent(indentLevel) .. "}" end return tableText end MAX_TABLE_LEVELS = 10 function c4_log:PrintTable(tValue, tableText, sIndent, level) tableText = tableText or "" level = level + 1 if (level <= MAX_TABLE_LEVELS) then if (type(tValue) == "table") then for k,v in pairs(tValue) do if (tableText == "") then tableText = sIndent .. tostring(k) .. ": " .. tostring(v) if (sIndent == ". ") then sIndent = " " end else tableText = tableText .. "\n" .. sIndent .. tostring(k) .. ": " .. tostring(v) end if (type(v) == "table") then tableText = self:PrintTable(v, tableText, sIndent .. " ", level) end end else tableText = tableText .. "\n" .. sIndent .. tostring(tValue) end end return tableText end function c4_log:LogTable(tValue, sIndent, level) level = level + 1 if (level <= MAX_TABLE_LEVELS) then if (type(tValue) == "table") then for k,v in pairs(tValue) do C4:ErrorLog(self._logName .. ": " .. sIndent .. tostring(k) .. ": " .. tostring(v)) if (type(v) == "table") then self:LogTable(v, sIndent .. " ", level) end end else C4:ErrorLog(self._logName .. ": " .. sIndent .. tValue) end end end function c4_log:Print(logLevel, sLogText) if (self._logLevel >= logLevel) then if (type(sLogText) == "table") then if (self._outputPrint) then print (self:PrintTable(sLogText, tableText, ". ", 0)) end if (self._outputC4Log) then self:LogTable(sLogText, " ", 0) end return end if (self._outputPrint) then print (sLogText) end if (self._outputC4Log) then C4:ErrorLog(self._logName .. ": " .. tostring(sLogText)) end end end function c4_log:Fatal(sLogText, ...) self:LogOutput(0, sLogText, ...) end function c4_log:Error(sLogText, ...) self:LogOutput(1, sLogText, ...) end function c4_log:Warn(sLogText, ...) self:LogOutput(2, sLogText, ...) end function c4_log:Info(sLogText, ...) self:LogOutput(3, sLogText, ...) end function c4_log:Debug(sLogText, ...) self:LogOutput(4, sLogText, ...) end function c4_log:Trace(sLogText, ...) self:LogOutput(5, sLogText, ...) end function c4_log:LogOutput(level, sLogText, ...) if (LogEnabled()) then if (type(sLogText) == "string") then sLogText = string.format(sLogText, ...) end self:Print(level, sLogText) end end --[[============================================================================= c4_log wrapper functions ===============================================================================]] function TryLog(level, sLogText, ...) LOG:LogOutput(level, sLogText, ...) end --[[============================================================================= SetLogLevel(level) Description: Sets the desired log level to view Parameters: level(int) - The logging level to set the message to 0 = Fatal 1 = Error 2 = Warn 3 = Info 4 = Debug 5 = Trace Returns: None ===============================================================================]] function SetLogLevel(level) LOG:SetLogLevel(level) end --[[============================================================================= LogLevel() Description: Returns the currently set log level Parameters: None Returns: The current log level 0 = Fatal 1 = Error 2 = Warn 3 = Info 4 = Debug 5 = Trace ===============================================================================]] function LogLevel() return LOG:LogLevel() end --[[============================================================================= OutputPrint(value) Description: Specifies whether to output log messages or not Parameters: value(bool) - true to enable logging output, false otherwise Returns: None ===============================================================================]] function OutputPrint(value) LOG:OutputPrint(value) end --[[============================================================================= OutputPrint(value) Description: Specifies whether to output log messages to file or not Parameters: value(bool) - true to enable logging output, false otherwise Returns: None ===============================================================================]] function OutputC4Log(value) LOG:OutputC4Log(value) end --[[============================================================================= SetLogName(logName) Description: Sets the name of the log file where the messages will be written to Parameters: logName(string) - Sets the name of the log to write messages to Returns: None ===============================================================================]] function SetLogName(logName) LOG:SetLogName(logName) end --[[============================================================================= LogName(logName) Description: Gets the name of the log file where the messages will be written to Parameters: None Returns: The value of the log file that has been set ===============================================================================]] function LogName() return LOG:LogName() end --[[============================================================================= LogEnabled() Description: Identifies if logging or print has been enabled Parameters: None Returns: true if either logging or print has been enabled, false otherwise ===============================================================================]] function LogEnabled() return LOG:Enabled() end --[[============================================================================= PrintEnabled() Description: Gets the state of print output Parameters: None Returns: true if print has been enabled, false otherwise ===============================================================================]] function PrintEnabled() return LOG:PrintEnabled() end --[[============================================================================= C4LogEnabled() Description: Gets the state of logging Parameters: None Returns: true if logging has been enabled, false otherwise ===============================================================================]] function C4LogEnabled() return LOG:C4LogEnabled() end --[[============================================================================= LogFatal(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Fatal(0) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogFatal(sLogText, ...) local status, err = pcall(TryLog, 0, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogFatal failed: " .. err) end end --[[============================================================================= LogError(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Error(1) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogError(sLogText, ...) local status, err = pcall(TryLog, 1, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogError failed: " .. err) end end --[[============================================================================= LogWarn(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Warn(2) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogWarn(sLogText, ...) local status, err = pcall(TryLog, 2, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogWarn failed: " .. err) end end --[[============================================================================= LogInfo(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Info(3) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogInfo(sLogText, ...) local status, err = pcall(TryLog, 3, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogInfo failed: " .. err) end end --[[============================================================================= LogDebug(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Debug(5) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogDebug(sLogText, ...) local status, err = pcall(TryLog, 4, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogDebug failed: " .. err) end end --[[============================================================================= LogTrace(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Trace(4) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogTrace(sLogText, ...) local status, err = pcall(TryLog, 5, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogTrace failed: " .. err) end end function dbgPrint(buf) if (LOG:PrintEnabled()) then print (buf) end end function dbgHexdump(buf) hexdump(buf, dbgPrint) end --[[============================================================================= c4_log unit tests ===============================================================================]] function __test_c4_log() require "test.C4Virtual" local LOG = c4_log:new("test_c4_log") assert(LOG:LogName() == "test_c4_log", "_logName is not equal to 'test_c4_log' it is: " .. LOG:LogName()) -- Test setting log level LOG:SetLogLevel("2 - Warning") assert(LOG:LogLevel() == 2, "_logLevel is not equal to '2' it is: " .. LOG:LogLevel()) LOG:SetLogLevel(3) assert(LOG:LogLevel() == 3, "_logLevel is not equal to '3' it is: " .. LOG:LogLevel()) -- Test enabling logs LOG:OutputPrint(false) assert(LOG:PrintEnabled() == false, "_outputPrint is not equal to 'false' it is: " .. tostring(LOG:PrintEnabled())) LOG:OutputC4Log(true) assert(LOG:C4LogEnabled() == true, "_outputC4Log is not equal to 'true' it is: " .. tostring(LOG:C4LogEnabled())) LOG:SetLogLevel(4) LogTrace("***** This is a test *****") end function __test_CreatTableText() local tTest = {} tTest[1] = {} tTest[2] = {} tTest[3] = 30 tTest[4] = "Forty" LogTrace("----- tText -----") LogTrace(tTest) local tTest2 = { One = {}, Two = {}, Three = 30, Four = "Forty" } LogTrace("----- tText2 -----") LogTrace(tTest2) local tTest3 = { [1] = {}, [2] = {}, [3] = 30, [4] = "Forty" } LogTrace("----- tText3 -----") LogTrace(tTest3) local tTest4 = { [1] = {}, Two = {}, [3] = 30, [4] = "Forty", Five = "Fifty" } LogTrace("----- tText4 -----") LogTrace(tTest4) local tableText = LOG:CreateTableText(tTest4) LogTrace("----- tableText -----") LogTrace(tableText) --local tNew = {[1] = {},[3] = 30,[4] = 'Forty',Five = 'Fifty',Two = {},} --LogTrace(tNew) end function __TestCreateTableTextFormatted() require "test.C4Virtual" local LOG = c4_log:new("test_c4_log") local tButtons = { Name = 'heat', Attributes = {}, ChildNodes = { [1] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '51', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = { Value = 'Pool Heater', Attributes = {}, Name = 'button_text', ChildNodes = {}, }, [3] = { Value = 'POOLHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, }, }, [2] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '53', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = { Value = 'Spa Heater', Attributes = {}, Name = 'button_text', ChildNodes = {}, }, [3] = { Value = 'SPAHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, }, }, [3] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '54', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = {Value = 'Pool Solar Heater', Attributes = {}, Name = 'button_text', ChildNodes = {} }, [3] = { Value = 'SOLHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, } } } } print(LOG:CreateTableTextFormatted(tButtons)) end
apache-2.0
kitala1/darkstar
scripts/globals/mobskills/Glacial_Breath.lua
7
1286
--------------------------------------------- -- Glacial Breath -- -- Description: Deals Ice damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Jormungand and Isgebind --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif(target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_ICE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/plate_of_fatty_tuna_sushi.lua
35
1540
----------------------------------------- -- ID: 5153 -- Item: plate_of_fatty_tuna_sushi -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 16 -- Ranged ACC 16 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5153); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_ACCP, 16); target:addMod(MOD_RACC, 16); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_ACCP, 16); target:delMod(MOD_RACC, 16); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
sylvanaar/IDLua
testdata/non-test-system-files/lua5.1-tests/strings.lua
11
6046
print('testing strings and string library') assert('alo' < 'alo1') assert('' < 'a') assert('alo\0alo' < 'alo\0b') assert('alo\0alo\0\0' > 'alo\0alo\0') assert('alo' < 'alo\0') assert('alo\0' > 'alo') assert('\0' < '\1') assert('\0\0' < '\0\1') assert('\1\0a\0a' <= '\1\0a\0a') assert(not ('\1\0a\0b' <= '\1\0a\0a')) assert('\0\0\0' < '\0\0\0\0') assert(not('\0\0\0\0' < '\0\0\0')) assert('\0\0\0' <= '\0\0\0\0') assert(not('\0\0\0\0' <= '\0\0\0')) assert('\0\0\0' <= '\0\0\0') assert('\0\0\0' >= '\0\0\0') assert(not ('\0\0b' < '\0\0a\0')) print('+') assert(string.sub("123456789",2,4) == "234") assert(string.sub("123456789",7) == "789") assert(string.sub("123456789",7,6) == "") assert(string.sub("123456789",7,7) == "7") assert(string.sub("123456789",0,0) == "") assert(string.sub("123456789",-10,10) == "123456789") assert(string.sub("123456789",1,9) == "123456789") assert(string.sub("123456789",-10,-20) == "") assert(string.sub("123456789",-1) == "9") assert(string.sub("123456789",-4) == "6789") assert(string.sub("123456789",-6, -4) == "456") assert(string.sub("\000123456789",3,5) == "234") assert(("\000123456789"):sub(8) == "789") print('+') assert(string.find("123456789", "345") == 3) a,b = string.find("123456789", "345") assert(string.sub("123456789", a, b) == "345") assert(string.find("1234567890123456789", "345", 3) == 3) assert(string.find("1234567890123456789", "345", 4) == 13) assert(string.find("1234567890123456789", "346", 4) == nil) assert(string.find("1234567890123456789", ".45", -9) == 13) assert(string.find("abcdefg", "\0", 5, 1) == nil) assert(string.find("", "") == 1) assert(string.find('', 'aaa', 1) == nil) assert(('alo(.)alo'):find('(.)', 1, 1) == 4) print('+') assert(string.len("") == 0) assert(string.len("\0\0\0") == 3) assert(string.len("1234567890") == 10) assert(#"" == 0) assert(#"\0\0\0" == 3) assert(#"1234567890" == 10) assert(string.byte("a") == 97) assert(string.byte("á") > 127) assert(string.byte(string.char(255)) == 255) assert(string.byte(string.char(0)) == 0) assert(string.byte("\0") == 0) assert(string.byte("\0\0alo\0x", -1) == string.byte('x')) assert(string.byte("ba", 2) == 97) assert(string.byte("\n\n", 2, -1) == 10) assert(string.byte("\n\n", 2, 2) == 10) assert(string.byte("") == nil) assert(string.byte("hi", -3) == nil) assert(string.byte("hi", 3) == nil) assert(string.byte("hi", 9, 10) == nil) assert(string.byte("hi", 2, 1) == nil) assert(string.char() == "") assert(string.char(0, 255, 0) == "\0\255\0") assert(string.char(0, string.byte("á"), 0) == "\0á\0") assert(string.char(string.byte("ál\0óu", 1, -1)) == "ál\0óu") assert(string.char(string.byte("ál\0óu", 1, 0)) == "") assert(string.char(string.byte("ál\0óu", -10, 100)) == "ál\0óu") print('+') assert(string.upper("ab\0c") == "AB\0C") assert(string.lower("\0ABCc%$") == "\0abcc%$") assert(string.rep('teste', 0) == '') assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê') assert(string.rep('', 10) == '') assert(string.reverse"" == "") assert(string.reverse"\0\1\2\3" == "\3\2\1\0") assert(string.reverse"\0001234" == "4321\0") for i=0,30 do assert(string.len(string.rep('a', i)) == i) end assert(type(tostring(nil)) == 'string') assert(type(tostring(12)) == 'string') assert(''..12 == '12' and type(12 .. '') == 'string') assert(string.find(tostring{}, 'table:')) assert(string.find(tostring(print), 'function:')) assert(tostring(1234567890123) == '1234567890123') assert(#tostring('\0') == 1) assert(tostring(true) == "true") assert(tostring(false) == "false") print('+') x = '"ílo"\n\\' assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\') assert(string.format('%q', "\0") == [["\000"]]) assert(string.format("\0%c\0%c%x\0", string.byte("á"), string.byte("b"), 140) == "\0á\0b8c\0") assert(string.format('') == "") assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) == string.format("%c%c%c%c", 34, 48, 90, 100)) assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be') assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023") assert(tonumber(string.format("%f", 10.3)) == 10.3) x = string.format('"%-50s"', 'a') assert(#x == 52) assert(string.sub(x, 1, 4) == '"a ') assert(string.format("-%.20s.20s", string.rep("%", 2000)) == "-"..string.rep("%", 20)..".20s") assert(string.format('"-%20s.20s"', string.rep("%", 2000)) == string.format("%q", "-"..string.rep("%", 2000)..".20s")) -- longest number that can be formated assert(string.len(string.format('%99.99f', -1e308)) >= 100) assert(loadstring("return 1\n--comentário sem EOL no final")() == 1) assert(table.concat{} == "") assert(table.concat({}, 'x') == "") assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2") local a = {}; for i=1,3000 do a[i] = "xuxu" end assert(table.concat(a, "123").."123" == string.rep("xuxu123", 3000)) assert(table.concat(a, "b", 20, 20) == "xuxu") assert(table.concat(a, "", 20, 21) == "xuxuxuxu") assert(table.concat(a, "", 22, 21) == "") assert(table.concat(a, "3", 2999) == "xuxu3xuxu") a = {"a","b","c"} assert(table.concat(a, ",", 1, 0) == "") assert(table.concat(a, ",", 1, 1) == "a") assert(table.concat(a, ",", 1, 2) == "a,b") assert(table.concat(a, ",", 2) == "b,c") assert(table.concat(a, ",", 3) == "c") assert(table.concat(a, ",", 4) == "") local locales = { "ptb", "ISO-8859-1", "pt_BR" } local function trylocale (w) for _, l in ipairs(locales) do if os.setlocale(l, w) then return true end end return false end if not trylocale("collate") then print("locale not supported") else assert("alo" < "álo" and "álo" < "amo") end if not trylocale("ctype") then print("locale not supported") else assert(string.gsub("áéíóú", "%a", "x") == "xxxxx") assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ") assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx") assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO") end os.setlocale("C") assert(os.setlocale() == 'C') assert(os.setlocale(nil, "numeric") == 'C') print('OK')
apache-2.0
kaustavha/rackspace-monitoring-agent
tests/tls/init.lua
4
5793
--[[ Copyright 2012 Rackspace 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 tlsbinding = require('_tls') local fs = require('fs') exports = {} no = {} local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local caPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] exports['test_set_key'] = function(test, asserts) local sc = tlsbinding.secure_context() local err, res = pcall(sc.setKey, sc, "foooooooo") asserts.equals(err, false) err, res = pcall(sc.setKey, sc, keyPem) asserts.equals(err, true) sc:close() test.done() end exports['test_set_cert'] = function(test, asserts) local sc = tlsbinding.secure_context() local err, res = pcall(sc.setCert, sc, "barrrrrr") asserts.equals(err, false) err, res = pcall(sc.setCert, sc, certPem) asserts.equals(err, true) sc:close() test.done() end exports['test_set_ciphers'] = function(test, asserts) local sc = tlsbinding.secure_context() local err, res = pcall(sc.setCiphers, sc, "barrrrrr") -- invalid cipher asserts.equals(err, false) err, res = pcall(sc.setCiphers, sc, "AES256-SHA") asserts.equals(err, true) sc:close() test.done() end exports['test_set_options'] = function(test, asserts) local sc = tlsbinding.secure_context() local err, res = pcall(sc.setOptions, sc, "barrrrrr") -- expected string asserts.equals(err, false) asserts.ok(tlsbinding.SSL_OP_ALL) err, res = pcall(sc.setOptions, sc, tlsbinding.SSL_OP_ALL) asserts.equals(err, true) sc:close() test.done() end exports['test_add_trusted_cert'] = function(test, asserts) local sc = tlsbinding.secure_context() local err, res = pcall(sc.addTrustedCert, sc, 1) -- invalid cert asserts.equals(err, false) err, res = pcall(sc.addTrustedCert, sc, certPem) asserts.equals(err, true) -- TODO: test a second unique cert added here works -- OpenSSL rejects adding the same cert twice to the x509 Store err, res = pcall(sc.addTrustedCert, sc, certPem) asserts.equals(err, false) sc:close() test.done() end return exports
apache-2.0
Roblox/Core-Scripts
PlayerScripts/StarterPlayerScripts/CameraScript/RootCamera/WatchCamera.lua
1
1674
local PlayersService = game:GetService('Players') local RootCameraCreator = require(script.Parent) local ZERO_VECTOR2 = Vector2.new(0, 0) local CFrame_new = CFrame.new local function CreateWatchCamera() local module = RootCameraCreator() module.PanEnabled = false local lastUpdate = tick() function module:Update() local now = tick() local camera = workspace.CurrentCamera local player = PlayersService.LocalPlayer if lastUpdate == nil or now - lastUpdate > 1 then module:ResetCameraLook() self.LastZoom = nil end local subjectPosition = self:GetSubjectPosition() if subjectPosition and player and camera then local cameraLook = nil local humanoid = self:GetHumanoid() if humanoid and humanoid.Torso then -- TODO: let the paging buttons move the camera but not the mouse/touch -- currently neither do local diffVector = subjectPosition - camera.CFrame.p cameraLook = diffVector.unit if self.LastZoom and self.LastZoom == self:GetCameraZoom() then -- Don't clobber the zoom if they zoomed the camera local zoom = diffVector.magnitude self:ZoomCamera(zoom) end end local zoom = self:GetCameraZoom() if zoom <= 0 then zoom = 0.1 end local newLookVector = self:RotateVector(cameraLook or self:GetCameraLook(), self.RotateInput) self.RotateInput = ZERO_VECTOR2 local newFocus = CFrame_new(subjectPosition) local newCamCFrame = CFrame_new(newFocus.p - (zoom * newLookVector), subjectPosition) camera.Focus = newFocus camera.CFrame = newCamCFrame self.LastZoom = zoom end lastUpdate = now end return module end return CreateWatchCamera
apache-2.0
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Matifa.lua
37
1026
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Matifa -- Type: Standard NPC -- @pos -10.583 -1 -8.820 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x021d); 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
crabman77/minetest-minetestforfun-server
mods/mobs/dungeonmaster.lua
6
3304
-- Dungeon Master by PilzAdam mobs:register_mob("mobs:dungeon_master", { -- animal, monster, npc, barbarian type = "monster", -- aggressive, shoots fireballs at player, deal 9 damages passive = false, pathfinding = false, damage = 9, attack_type = "dogshoot", reach = 3, shoot_interval = 2.5, arrow = "mobs:fireball", shoot_offset = 1, -- health & armor hp_min = 30, hp_max = 40, armor = 80, -- textures and model collisionbox = {-0.7, -1, -0.7, 0.7, 1.6, 0.7}, visual = "mesh", mesh = "mobs_dungeon_master.b3d", textures = { {"mobs_dungeon_master.png"}, {"mobs_dungeon_master_cobblestone.png"}, {"mobs_dungeon_master_strangewhite.png"}, }, blood_texture = "mobs_blood.png", -- sounds makes_footstep_sound = true, sounds = { random = "mobs_dungeonmaster", shoot_attack = "mobs_fireball", }, -- speed and jump walk_velocity = 1, run_velocity = 2, jump = false, view_range = 16, knock_back = 0.05, -- Very small knockback -- drops mese or diamond when dead drops = { {name = "mobs:dungeon_master_blood", chance = 2, min = 1, max = 2,}, {name = "default:diamond", chance = 4, min = 1, max = 3,}, {name = "default:mese_crystal", chance = 4, min = 3, max = 6,}, {name = "mobs:dungeon_master_diamond", chance = 6, min = 1, max = 1,}, {name = "maptools:gold_coin", chance = 20, min = 1, max = 1,}, {name = "default:diamondblock", chance = 33, min = 1, max = 1,}, {name = "runes:scroll_watchdog", chance = 130, min = 1, max = 5}, }, -- damaged by water_damage = 1, lava_damage = 1, light_damage = 0, fear_height = 3, -- model animation animation = { stand_start = 0, stand_end = 19, walk_start = 20, walk_end = 35, punch_start = 36, punch_end = 48, speed_normal = 15, speed_run = 15, }, }) -- spawn on stone between 20 and -1 light, 1 in 10000 chance, 1 dungeon master in area starting at -100 and below mobs:spawn_specific("mobs:dungeon_master", {"default:stone", "default:sandstone", "nether:netherrack"}, {"air"}, -1, 20, 30, 10000, 1, -31000, -250, false) -- register spawn egg mobs:register_egg("mobs:dungeon_master", "Dungeon Master", "mobs_dongeon_master_inv.png", 1) -- fireball (weapon) mobs:register_arrow("mobs:fireball", { visual = "sprite", visual_size = {x = 1, y = 1}, textures = {"mobs_fireball.png"}, velocity = 6, -- direct hit, no fire... just plenty of pain hit_player = function(self, player) player:punch(self.object, 1.0, { -- Mettre à 2.5 aussi ? full_punch_interval = 2.5, -- Modif MFF damage_groups = {fleshy = 9}, -- Modif MFF }, nil) end, hit_mob = function(self, player) player:punch(self.object, 1.0, { -- Mettre à 2.5 aussi ? full_punch_interval = 2.5, -- Modif MFF damage_groups = {fleshy = 9}, -- Modif MFF }, nil) end, -- node hit, bursts into flame (cannot blast through obsidian or protection redo mod items) hit_node = function(self, pos, node) mobs:explosion(pos, 1, 1, 0) end }) minetest.register_craftitem("mobs:dungeon_master_blood", { description = "Dungeon Master Blood", inventory_image = "mobs_dungeon_master_blood.png", groups = {magic = 1}, }) minetest.register_craftitem("mobs:dungeon_master_diamond", { description = "Dungeon Master Diamond", inventory_image = "mobs_dungeon_master_diamond.png", groups = {magic = 1}, })
unlicense
kitala1/darkstar
scripts/zones/RuLude_Gardens/npcs/_6r8.lua
17
2376
----------------------------------- -- Area: Ru'Lud Gardens -- Door: Windurstian Ambassador -- Windurst Missions 3.3 "A New Journey" and 4.1 "Magicite" -- @pos 31 9 -22 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) pNation = player:getNation(); currentMission = player:getCurrentMission(pNation); MissionStatus = player:getVar("MissionStatus"); if(currentMission == A_NEW_JOURNEY and MissionStatus == 4) then player:startEvent(0x0028); elseif(player:getRank() == 4 and MissionStatus == 0 and player:getCurrentMission(WINDURST) == 255 and getMissionRankPoints(player,13) == 1) then if(player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then player:startEvent(0x0083,1); else player:startEvent(0x0083); end elseif(player:getRank() >= 4) then player:messageSpecial(WINDURST_EMBASSY); -- restricted area else player:messageSpecial(WINDURST_EMBASSY + 1); -- you have no letter of introduction end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0028) then finishMissionTimeline(player,1,csid,option); elseif(csid == 0x0083 and option == 1) then player:setVar("MissionStatus",1); if(player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) == false) then player:addKeyItem(ARCHDUCAL_AUDIENCE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,ARCHDUCAL_AUDIENCE_PERMIT); end elseif(csid == 0x0026 or csid == 0x0023) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/limbus.lua
6
39128
require("scripts/globals/keyitems"); -- require("scripts/globals/limbus"); APPOLLYON_SE_NE = 1; --out 557 -1 441 128 APPOLLYON_NW_SW = 2; --out -561 0 443 242 TEMENOS = 3; --WHITE_CARD = 349; --RED_CARD = 350; --BLACK_CARD = 351; --COSMOCLEANSE = 734; -- REGION NW_Apollyon =1; SW_Apollyon =2; NE_Apollyon =3; SE_Apollyon =4; CS_Apollyon =5; Central_Apollyon =6; Temenos_Western_Tower=1; Temenos_Northern_Tower=2; Temenos_Eastern_Tower=3; Central_Temenos_Basement=4; Central_Temenos_1st_Floor=5; Central_Temenos_2nd_Floor=6; Central_Temenos_3rd_Floor=7; Central_Temenos_4th_Floor=8; APPOLLYON_SE_NE_BCNM_LIST = { --instanceID ,white ,red ,black,bitmap,bit,instanceRegion 1292,{false,false,true,8,NE_Apollyon}, -- 'NE_Apollyon' region 3 438 0 -89 1293,{false,false,true,4,SE_Apollyon}, -- 'SE_Apollyon' 468 0 -625 1294,{false,false,false,32,CS_Apollyon}, -- 'CS_Apollyon' 0 0 -210 1295,{false,false,false,64,CS_Apollyon}, -- 'CS_Apollyon_II' 0 0 -133 1296,{false,false,false,16,Central_Apollyon}, -- 'Central_Apollyon' 0 0 210 1297,{false,false,false,128,Central_Apollyon} -- 'Central_Apollyon_II' 0 0 210 }; APPOLLYON_NW_SW_BCNM_LIST = { 1290,{false,true,false,2,NW_Apollyon}, -- 'NW_Apollyon' -439 0 -89 1291,{false,true,false,1,SW_Apollyon}, -- 'SW_Apollyon' -468 0 -626 1294,{false,false,false,32,CS_Apollyon}, -- 'CS_Apollyon' 0 0 -210 1295,{false,false,false,64,CS_Apollyon}, -- 'CS_Apollyon_II' 0 0 -133 1296,{false,false,false,16,Central_Apollyon}, -- 'Central_Apollyon' 0 0 210 1297,{false,false,false,128,Central_Apollyon} -- 'Central_Apollyon_II' 0 0 210 }; TEMENOS_LIST = { 1298,{true,false,false,4,Temenos_Western_Tower}, -- 'Temenos_Western_Tower' 380 71 -184 1299,{true,false,false,1,Temenos_Northern_Tower}, -- 'Temenos_Northern_Tower' 380 71 375 1300,{true,false,false,2,Temenos_Eastern_Tower}, -- 'Temenos_Eastern_Tower' 380 -2 96 1301,{false,false,false,128,Central_Temenos_Basement}, -- 'Central_Temenos_Basement' 580 -2 -544 1302,{false,false,false,256,Central_Temenos_Basement}, -- 'Central_Temenos_Basement_II' 540 -2 -544 1303,{false,false,false,64,Central_Temenos_1st_Floor}, -- 'Central_Temenos_1st_Floor' 260 -162 -504 1304,{false,false,false,32,Central_Temenos_2nd_Floor}, -- 'Central_Temenos_2nd_Floor' 20 -2 -544 1305,{false,false,false,16,Central_Temenos_3rd_Floor}, -- 'Central_Temenos_3rd_Floor' -296 -162 -500 1306,{false,false,false,8,Central_Temenos_4th_Floor}, -- 'Central_Temenos_4th_Floor' -540 -2 -584 1307,{false,false,false,512,Central_Temenos_4th_Floor} -- 'Central_Temenos_4th_Floor_II' -540 -2 -584 }; MIMICPOSITION={ 1,{-363,0,-282}; 2,{-359,0,-277}; 3,{-326,0,-301}; 4,{-331,0,-330}; 5,{-340,0,-330}; 6,{-345,0,-311}; 7,{-339,0,-300}; 8,{-335,0,-281}; }; -- armoryID,(type,regionID,time, despawnothercoffer, mimicID ,lootID) STATUS_NORMAL = 0; STATUS_DISAPPEAR = 2; cTIME=1 cITEM=2 cRESTORE=3; cMIMIC=4; ARMOURY_CRATES_LIST_APPOLLYON= { -- appolyon list 1 ,{cTIME,SE_Apollyon,5,false,0,0}, -- time SE_Appollyon floor 1 2 ,{cITEM,SE_Apollyon,0,false,0,110}, -- items SE_Appollyon floor 1 3 ,{cRESTORE,SE_Apollyon,0,false,0,0}, -- restore SE_Appollyon floor 1 14 ,{cTIME,SW_Apollyon,10,false,0,0}, -- time SW_Appollyon floor 1 15 ,{cITEM,SW_Apollyon,0,false,0,119}, -- items SW_Appollyon floor 1 16 ,{cRESTORE,SW_Apollyon,0,false,0,0}, -- restore SW_Appollyon floor 1 --32 ,{}, --mimic --33 ,{}, --mimic --34 ,{}, --mimic --35 ,{}, --mimic --36 ,{}, --mimic --37 ,{}, --mimic --38 ,{}, --mimic 39 ,{cITEM,Central_Apollyon,0,false,0,128}, -- omega 40 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 1 T1 41 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 1 T2 42 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 1 T3 43 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 2 T1 44 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 2 T2 45 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 2 T3 70 ,{cTIME,SW_Apollyon,10,true,0,0}, -- time SW_Appollyon floor 2 71 ,{cITEM,SW_Apollyon,0,true,0,120}, -- items SW_Appollyon floor 2 72 ,{cRESTORE,SW_Apollyon,0,true,0,0}, -- restore SW_Appollyon floor 2 81 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 1 T2 82 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 1 T3 83 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 2 T2 84 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 2 T3 85 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 3 T2 94 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 3 T3 95 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 4 T2 96 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 4 T3 97 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 4 T2 98 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 4 T3 107 ,{cITEM,NW_Apollyon,0,false,0,123},-- item NW_Appollyon floor 1 108 ,{cITEM,NW_Apollyon,0,false,0,124},-- item NW_Appollyon floor 2 109 ,{cITEM,NW_Apollyon,0,false,0,125},-- item NW_Appollyon floor 3 110 ,{cITEM,NW_Apollyon,0,false,0,126}, -- item NW_Appollyon floor 4 111 ,{cITEM,NW_Apollyon,0,false,0,127}, -- item NW_Appollyon floor 5 118 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 1 T1 119 ,{cITEM,NE_Apollyon,0,false,0,114}, -- items NE_Appollyon floor 1 120 ,{cRESTORE,NE_Apollyon,0,false,0,0}, -- restore NE_Appollyon floor 1 125 ,{cTIME,NE_Apollyon,5,false,0,10}, -- time NE_Appollyon floor 2 T1 126 ,{cITEM,NE_Apollyon,0,false,0,115}, -- items NE_Appollyon floor 2 127 ,{cRESTORE,NE_Apollyon,0,false,0,0}, -- restore NE_Appollyon floor 2 139 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 3 T1 140 ,{cITEM,NE_Apollyon,0,false,0,116}, -- items NE_Appollyon floor 3 141 ,{cRESTORE,NE_Apollyon,0,false,0,0}, -- restore NE_Appollyon floor 3 153 ,{cTIME,NE_Apollyon,5,false,0,0}, -- time NE_Appollyon floor 4 T1 154 ,{cITEM,NE_Apollyon,0,false,0,117}, -- items NE_Appollyon floor 4 155 ,{cRESTORE,NE_Apollyon,0,false,0,0}, -- restore NE_Appollyon floor 4 177 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Apollyon floor 3 T1 178 ,{cITEM,NE_Apollyon,0,false,0,118}, -- items NE_Appollyon floor 5 179 ,{cRESTORE,NW_Apollyon,0,false,0,0}, -- restore NW_Apollyon floor 4 189 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 3 T2 190 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 3 T3 195 ,{cTIME,SW_Apollyon,10,false,0,0}, -- time SW_Appollyon floor 3 196 ,{cITEM,SW_Apollyon,5,false,0,121}, -- items SW_Appollyon floor 3 197 ,{cRESTORE,SW_Apollyon,0,false,0,0}, -- restore SW_Appollyon floor 3 210 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 211 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 212 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 213 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 214 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 215 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 216 ,{cMIMIC,SW_Apollyon,0,false,0,0}, --PH for mimic 232 ,{cTIME,SE_Apollyon,5,false,0,0}, -- time SE_Appollyon floor 2 233 ,{cITEM,SE_Apollyon,0,false,0,111}, -- items SE_Appollyon floor 2 234 ,{cRESTORE,SE_Apollyon,0,false,0,0}, -- restore SE_Appollyon floor 2 246 ,{cTIME,SE_Apollyon,10,false,0,0}, -- time SE_Appollyon floor 3 247 ,{cITEM,SE_Apollyon,0,false,0,112}, -- items SE_Appollyon floor 3 248 ,{cRESTORE,SE_Apollyon,0,false,0,0}, -- restore SE_Appollyon floor 3 259 ,{cITEM,Central_Apollyon,0,false,0,129}, -- Pod 262 ,{cTIME,NW_Apollyon,5,false,0,0}, -- time NW_Appollyon floor 4 T1 263 ,{cITEM,SE_Apollyon,0,false,0,113}, -- items SE_Appollyon floor 4 264 ,{cRESTORE,NW_Apollyon,0,false,0,0}, -- restore NW_Apollyon floor 1 289 ,{cRESTORE,NW_Apollyon,0,false,0,0}, -- restore NW_Apollyon floor 2 313 ,{cITEM,SW_Apollyon,0,false,0,122}, -- items SW_Appollyon floor 4 327 ,{cRESTORE,NW_Apollyon,0,false,0,0}, -- restore NW_Apollyon floor 3 --:::::::::::::::::::::::::::::::::::::::::::::::::::::::: } ARMOURY_CRATES_LIST_TEMENOS={ 1 ,{cITEM,Temenos_Western_Tower,0,false,0,137}, 2 ,{cITEM,Temenos_Western_Tower,0,false,0,138}, 3 ,{cITEM,Temenos_Western_Tower,0,false,0,139}, 10 ,{cITEM,Temenos_Western_Tower,0,false,0,140}, 11 ,{cITEM,Temenos_Western_Tower,0,false,0,141}, 12 ,{cITEM,Temenos_Western_Tower,0,false,0,142}, 17 ,{cITEM,Temenos_Western_Tower,0,false,0,143}, 18 ,{cITEM,Temenos_Northern_Tower,0,true,0,130},-- F1 19 ,{cITEM,Temenos_Northern_Tower,0,true,0,131},-- F2 26 ,{cITEM,Temenos_Northern_Tower,0,true,0,132},-- F3 27 ,{cITEM,Temenos_Northern_Tower,0,true,0,133},-- F4 28 ,{cITEM,Temenos_Northern_Tower,0,true,0,134},-- F5 38 ,{cITEM,Temenos_Northern_Tower,0,true,0,135},-- F6 39 ,{cITEM,Temenos_Northern_Tower,0,false,0,136},-- F7 40 ,{cITEM,Temenos_Eastern_Tower,0,true,0,144}, 45 ,{cITEM,Temenos_Eastern_Tower,0,true,0,145}, 46 ,{cITEM,Temenos_Eastern_Tower,0,true,0,146}, 47 ,{cITEM,Temenos_Eastern_Tower,0,true,0,147}, 68 ,{cITEM,Temenos_Eastern_Tower,0,true,0,148}, 69 ,{cITEM,Temenos_Eastern_Tower,0,true,0,149}, 70 ,{cITEM,Temenos_Eastern_Tower,0,true,0,150}, 71 ,{cITEM,Central_Temenos_1st_Floor,0,false,0,151}, 77 ,{cITEM,Central_Temenos_2nd_Floor,0,false,0,152}, 78 ,{cITEM,Central_Temenos_3rd_Floor,0,false,0,153}, -- central 4eme floor ------------------------------- 79 ,{cITEM,Central_Temenos_4th_Floor,0,false,0,154}, -- 80 ,{cITEM,Central_Temenos_4th_Floor,0,false,1,155}, 86 ,{cITEM,Central_Temenos_4th_Floor,0,false,1,155}, 87 ,{cITEM,Central_Temenos_4th_Floor,0,false,1,155}, 88 ,{cITEM,Central_Temenos_4th_Floor,0,false,1,155}, 89 ,{cITEM,Central_Temenos_4th_Floor,0,false,2,155}, 95 ,{cITEM,Central_Temenos_4th_Floor,0,false,2,155}, 96 ,{cITEM,Central_Temenos_4th_Floor,0,false,2,155}, 97 ,{cITEM,Central_Temenos_4th_Floor,0,false,2,155}, 98 ,{cITEM,Central_Temenos_4th_Floor,0,false,3,155}, 104 ,{cITEM,Central_Temenos_4th_Floor,0,false,3,155}, 105 ,{cITEM,Central_Temenos_4th_Floor,0,false,3,155}, 106 ,{cITEM,Central_Temenos_4th_Floor,0,false,3,155}, 107 ,{cITEM,Central_Temenos_4th_Floor,0,false,4,155}, 113 ,{cITEM,Central_Temenos_4th_Floor,0,false,4,155}, 114 ,{cITEM,Central_Temenos_4th_Floor,0,false,4,155}, 115 ,{cITEM,Central_Temenos_4th_Floor,0,false,5,155}, 116 ,{cITEM,Central_Temenos_4th_Floor,0,false,5,155}, 122 ,{cITEM,Central_Temenos_4th_Floor,0,false,5,155}, -- 123 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, 127 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, -- ----------------------------------------- 128 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 129 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 139 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 140 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 141 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 151 ,{cTIME,Temenos_Western_Tower,15,false,0,0}, 152 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F1 153 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F2 160 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F3 161 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F4 162 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F5 172 ,{cTIME,Temenos_Northern_Tower,15,true,0,0},-- F6 173 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 174 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 181 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 182 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 183 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 190 ,{cTIME,Temenos_Eastern_Tower,15,true,0,0}, 197 ,{cTIME,Central_Temenos_Basement,5,false,0,0}, 199 ,{cTIME,Central_Temenos_Basement,5,false,0,0}, 200 ,{cTIME,Central_Temenos_Basement,5,false,0,0}, 201 ,{cTIME,Central_Temenos_Basement,5,false,0,0}, 202 ,{cTIME,Central_Temenos_Basement,5,false,0,0}, 203 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 204 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 205 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 206 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 207 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 208 ,{cRESTORE,Temenos_Western_Tower,0,false,0,0}, 209 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F1 210 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F2 211 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F3 212 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F4 213 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F5 214 ,{cRESTORE,Temenos_Northern_Tower,0,true,0,0},-- F6 215 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 216 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 217 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 236 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 261 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 277 ,{cRESTORE,Temenos_Eastern_Tower,0,true,0,0}, 284 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, 321 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, 348 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, 360 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0}, 393 ,{cMIMIC,Temenos_Eastern_Tower,0,true,0,0} }; function LimbusEntrance(player,entrance) switch (entrance): caseof { [1] = function (x) player:setPos(643,0.1,-600,124,0x26); -- instance entrer 600 1 -600 end , -- sortiezone 637,-4,-642,642,4,-637 [2] = function (x) player:setPos(-668,0.1,-666,209,0x26); -- instance entrer -599 0 -600 end , -- sortiezone -642,-4,-642,-637,4,-637 } end; function ResetPlayerLimbusVariable(player) player:setVar("characterLimbusKey",0); player:setVar("LimbusID",0); end; function GenerateLimbusKey() local Key = math.random(1,1000000); while (IsKeyExist(Key)== true) do Key = math.random(1,1000000); end return Key; end; function HideArmouryCrates(Region,Zone) if(Zone == APPOLLYON_SE_NE or Zone == APPOLLYON_NW_SW)then for X = 1,table.getn (ARMOURY_CRATES_LIST_APPOLLYON),2 do if(ARMOURY_CRATES_LIST_APPOLLYON[X+1][2] == Region)then GetNPCByID((ARMOURY_CRATES_LIST_APPOLLYON[X])+16932864):setStatus(STATUS_DISAPPEAR); end end elseif(Zone == TEMENOS)then for X = 1,table.getn (ARMOURY_CRATES_LIST_TEMENOS),2 do if(ARMOURY_CRATES_LIST_TEMENOS[X+1][2] == Region)then GetNPCByID((ARMOURY_CRATES_LIST_TEMENOS[X])+16928768):setStatus(STATUS_DISAPPEAR); end end end end; function HideTemenosDoor(Region) if(Region==Temenos_Northern_Tower)then GetNPCByID((450)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((451)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((452)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((453)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((454)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((455)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((456)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Temenos_Eastern_Tower)then GetNPCByID((457)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((458)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((459)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((460)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((461)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((462)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((463)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Temenos_Western_Tower)then GetNPCByID((464)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((465)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((466)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((467)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((468)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((469)+16928770):setStatus(STATUS_DISAPPEAR); GetNPCByID((470)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Central_Temenos_1st_Floor)then GetNPCByID((471)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Central_Temenos_2nd_Floor)then GetNPCByID((472)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Central_Temenos_3rd_Floor)then GetNPCByID((473)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Central_Temenos_4th_Floor)then GetNPCByID((474)+16928770):setStatus(STATUS_DISAPPEAR); elseif(Region==Central_Temenos_Basement)then GetNPCByID((475)+16928770):setStatus(STATUS_DISAPPEAR); end end; function IselementalDayAreDead() local day = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local daykill=false; if(day==0)then -- fire if(IsMobDead(16932913)==true and IsMobDead(16932921)==true and IsMobDead(16932929)==true )then daykill=true; end elseif(day==1)then-- earth if(IsMobDead(16932912)==true and IsMobDead(16932920)==true and IsMobDead(16932928)==true )then daykill=true; end elseif(day==2)then-- water if(IsMobDead(16932916)==true and IsMobDead(16932924)==true and IsMobDead(16932932)==true )then daykill=true; end elseif(day==3)then-- wind if(IsMobDead(16932910)==true and IsMobDead(16932918)==true and IsMobDead(16932926)==true )then daykill=true; end elseif(day==4)then-- ice if(IsMobDead(16932914)==true and IsMobDead(16932922)==true and IsMobDead(16932930)==true )then daykill=true; end elseif(day==5)then-- lightning if(IsMobDead(16932917)==true and IsMobDead(16932925)==true and IsMobDead(16932933)==true )then daykill=true; end elseif(day==6)then-- ligth if(IsMobDead(16932931)==true and IsMobDead(16932915)==true and IsMobDead(16932923)==true )then daykill=true; end elseif(day==7)then -- dark if(IsMobDead(16932911)==true and IsMobDead(16932919)==true and IsMobDead(16932927)==true )then daykill=true; end end return daykill; end; -------------------------------------------------- -- alreadyReceived -- I use this function for TE and Boss Trigger -------------------------------------------------- function alreadyReceived(player,number,region) local LimbusVar = 0; local bit = {}; local pZone = player:getZoneID(); if(pZone == 37) then elseif(pZone == 38) then LimbusVar = GetServerVariable("[CS_Apollyon]Already_Received"); end for i = 12,0,-1 do twop = 2^i; if(LimbusVar >= twop) then bit[i+1] = 1; LimbusVar = LimbusVar - twop; else bit[i+1] = 0; end; end; -- printf("received %u",bit[number]); if(bit[number] == 0) then return false; else return true; end end; function addLimbusList(player,number,Region) local pZone = player:getZoneID(); if(pZone == 37) then elseif(pZone == 38) then SetServerVariable("[CS_Apollyon]Already_Received",GetServerVariable("[CS_Apollyon]Already_Received") + number); end end; function IsKeyExist(Key) -- return true if Key already exist for another linbus local H= false; local KeyAlreadyExist = { GetServerVariable("[NW_Apollyon]UniqueID"), GetServerVariable("[SW_Apollyon]UniqueID"), GetServerVariable("[NE_Apollyon]UniqueID"), GetServerVariable("[SE_Apollyon]UniqueID"), GetServerVariable("[CS_Apollyon]UniqueID"), GetServerVariable("[CS_Apollyon_II]UniqueID"), GetServerVariable("[Central_Apollyon]UniqueID"), GetServerVariable("[Central_Apollyon_II]UniqueID"), GetServerVariable("[Temenos_W_Tower]UniqueID"), GetServerVariable("[Temenos_N_Tower"), GetServerVariable("[Temenos_E_Tower]UniqueID"), GetServerVariable("[C_Temenos_Base]UniqueID"), GetServerVariable("[C_Temenos_Base_II]UniqueID"), GetServerVariable("[C_Temenos_1st]UniqueID"), GetServerVariable("[C_Temenos_2nd]UniqueID"), GetServerVariable("[C_Temenos_3rd]UniqueID"), GetServerVariable("[C_Temenos_4th]UniqueID"), GetServerVariable("[C_Temenos_4th_II]UniqueID"), }; for nl = 1, table.getn (KeyAlreadyExist),1 do if(KeyAlreadyExist[nl] == Key)then H= true; break; end end return H; end; function GetLimbusKeyFromInstance(instanceID) local Instancekey = 0; switch (instanceID): caseof { [1290] = function (x) Instancekey = GetServerVariable("[NW_Apollyon]UniqueID"); end , [1291] = function (x) Instancekey = GetServerVariable("[SW_Apollyon]UniqueID"); end , [1292] = function (x) Instancekey = GetServerVariable("[NE_Apollyon]UniqueID") ; end , [1293] = function (x) Instancekey = GetServerVariable("[SE_Apollyon]UniqueID"); end , [1294] = function (x) Instancekey = GetServerVariable("[CS_Apollyon]UniqueID"); end , [1295] = function (x) Instancekey = GetServerVariable("[CS_Apollyon_II]UniqueID"); end , [1296] = function (x) Instancekey = GetServerVariable("[Central_Apollyon]UniqueID"); end , [1297] = function (x) Instancekey = GetServerVariable("[Central_Apollyon_II]UniqueID"); end , [1298] = function (x) Instancekey = GetServerVariable("[Temenos_W_Tower]UniqueID"); end , [1299] = function (x) Instancekey = GetServerVariable("[Temenos_N_Tower"); end , [1300] = function (x) Instancekey = GetServerVariable("[Temenos_E_Tower]UniqueID"); end , [1301] = function (x) Instancekey = GetServerVariable("[C_Temenos_Base]UniqueID"); end , [1302] = function (x) Instancekey = GetServerVariable("[C_Temenos_Base_II]UniqueID"); end , [1303] = function (x) Instancekey = GetServerVariable("[C_Temenos_1st]UniqueID"); end , [1304] = function (x) Instancekey = GetServerVariable("[C_Temenos_2nd]UniqueID"); end , [1305] = function (x) Instancekey = GetServerVariable("[C_Temenos_3rd]UniqueID"); end , [1306] = function (x) Instancekey = GetServerVariable("[C_Temenos_4th]UniqueID"); end , [1307] = function (x) Instancekey = GetServerVariable("[C_Temenos_4th_II]UniqueID"); end , } -- print("Server_;_instanceID "..instanceID.." Serverkey "..Instancekey); return Instancekey ; end; function IsMobDead(mobID) local ActionValue=GetMobAction(mobID); if(ActionValue==0 or ActionValue==21 or ActionValue==22 or ActionValue==23)then return true; else return false; end end; function despawnLimbusCS() for n= 16933130,16933136,1 do if(IsMobDead(n)==false)then DespawnMob(n);end end for n= 16933138,16933143,1 do if(IsMobDead(n)==false)then DespawnMob(n);end end for n= 16933145,16933152,1 do if(IsMobDead(n)==false)then DespawnMob(n);end end end; function SpawnCofferSWfloor3() --print("spawn_coffer"); GetNPCByID(16932864+210):setPos(MIMICPOSITION[2][1],MIMICPOSITION[2][2],MIMICPOSITION[2][3]); GetNPCByID(16932864+210):setStatus(STATUS_NORMAL); GetNPCByID(16932864+211):setPos(MIMICPOSITION[4][1],MIMICPOSITION[4][2],MIMICPOSITION[4][3]); GetNPCByID(16932864+211):setStatus(STATUS_NORMAL); GetNPCByID(16932864+212):setPos(MIMICPOSITION[6][1],MIMICPOSITION[6][2],MIMICPOSITION[6][3]); GetNPCByID(16932864+212):setStatus(STATUS_NORMAL); GetNPCByID(16932864+213):setPos(MIMICPOSITION[8][1],MIMICPOSITION[8][2],MIMICPOSITION[8][3]); GetNPCByID(16932864+213):setStatus(STATUS_NORMAL); GetNPCByID(16932864+214):setPos(MIMICPOSITION[10][1],MIMICPOSITION[10][2],MIMICPOSITION[10][3]); GetNPCByID(16932864+214):setStatus(STATUS_NORMAL); GetNPCByID(16932864+215):setPos(MIMICPOSITION[12][1],MIMICPOSITION[12][2],MIMICPOSITION[12][3]); GetNPCByID(16932864+215):setStatus(STATUS_NORMAL); GetNPCByID(16932864+216):setPos(MIMICPOSITION[14][1],MIMICPOSITION[14][2],MIMICPOSITION[14][3]); GetNPCByID(16932864+216):setStatus(STATUS_NORMAL); SetServerVariable("[SW_Apollyon]MimicTrigger",1); end; function SpawnCofferTemenosCFloor4() --print("spawn_coffer"); GetNPCByID(16928768+80):setPos(-560,-6,-459); GetNPCByID(16928768+80):setStatus(STATUS_NORMAL); GetNPCByID(16928768+86):setPos(-540,-6,-459); GetNPCByID(16928768+86):setStatus(STATUS_NORMAL); GetNPCByID(16928768+87):setPos(-576,-6,-459); GetNPCByID(16928768+87):setStatus(STATUS_NORMAL); GetNPCByID(16928768+88):setPos(-528,-6,-459); GetNPCByID(16928768+88):setStatus(STATUS_NORMAL); GetNPCByID(16928768+89):setPos(-592,-6,-487); GetNPCByID(16928768+89):setStatus(STATUS_NORMAL); GetNPCByID(16928768+95):setPos(-566,-6,-486); GetNPCByID(16928768+95):setStatus(STATUS_NORMAL); GetNPCByID(16928768+96):setPos(-566,-6,-513); GetNPCByID(16928768+96):setStatus(STATUS_NORMAL); GetNPCByID(16928768+97):setPos(-592,-6,-513); GetNPCByID(16928768+97):setStatus(STATUS_NORMAL); GetNPCByID(16928768+98):setPos(-531,-0.5,-501); GetNPCByID(16928768+98):setStatus(STATUS_NORMAL); GetNPCByID(16928768+104):setPos(-527,-6,-512); GetNPCByID(16928768+104):setStatus(STATUS_NORMAL); GetNPCByID(16928768+105):setPos(-552,-6,-512); GetNPCByID(16928768+105):setStatus(STATUS_NORMAL); GetNPCByID(16928768+106):setPos(-552,-6,-488); GetNPCByID(16928768+106):setStatus(STATUS_NORMAL); GetNPCByID(16928768+107):setPos(-488,2,-510); GetNPCByID(16928768+107):setStatus(STATUS_NORMAL); GetNPCByID(16928768+113):setPos(-486,2,-491); GetNPCByID(16928768+113):setStatus(STATUS_NORMAL); GetNPCByID(16928768+114):setPos(-508,2,-513); GetNPCByID(16928768+114):setStatus(STATUS_NORMAL); GetNPCByID(16928768+115):setPos(-488,2,-408); GetNPCByID(16928768+115):setStatus(STATUS_NORMAL); GetNPCByID(16928768+116):setPos(-485,2,-423); GetNPCByID(16928768+116):setStatus(STATUS_NORMAL); GetNPCByID(16928768+122):setPos(-506,2,-406); GetNPCByID(16928768+122):setStatus(STATUS_NORMAL); end; function Randomcoffer(Floor,region) local cofferID=0; local cofferType=0; local spawnchance=math.random(0,100); if(spawnchance < 31)then if(spawnchance < 15)then cofferType=cITEM; elseif(spawnchance < 25)then cofferType=cRESTORE; elseif(spawnchance < 30)then cofferType=cTIME; end else -- print("nothing_spawn"); end if(region==Temenos_Western_Tower and cofferType==cITEM)then switch (Floor): caseof { [1] = function (x) cofferID=1; end, [2] = function (x) cofferID=2; end, [3] = function (x) cofferID=3; end, [4] = function (x) cofferID=10; end, [5] = function (x) cofferID=11; end, [6] = function (x) cofferID=12; end, } elseif(region==Temenos_Western_Tower and cofferType==cRESTORE)then switch (Floor): caseof { [1] = function (x) cofferID=203; end, [2] = function (x) cofferID=204; end, [3] = function (x) cofferID=205; end, [4] = function (x) cofferID=206; end, [5] = function (x) cofferID=207; end, [6] = function (x) cofferID=208; end, } elseif(region==Temenos_Western_Tower and cofferType==cTIME)then switch (Floor): caseof { [1] = function (x) cofferID=128; end, [2] = function (x) cofferID=129; end, [3] = function (x) cofferID=139; end, [4] = function (x) cofferID=140; end, [5] = function (x) cofferID=141; end, [6] = function (x) cofferID=151; end, } end -- print("cofferID" ..cofferID); return cofferID; end; function ResetKeyForEmptyLimbus(player,instanceID) instancestatus=player:isSpecialBattlefieldEmpty(GetInstanceRegion(instanceID)); -- print("instancestatus"..instancestatus); if(instancestatus==0)then switch (instanceID): caseof { [1290] = function (x) SetServerVariable("[NW_Apollyon]UniqueID",0); print("[NW_Apollyon]KeyDelete"); end , [1291] = function (x) SetServerVariable("[SW_Apollyon]UniqueID",0); print("[SW_Apollyon]KeyDelete"); end , [1292] = function (x) SetServerVariable("[NE_Apollyon]UniqueID",0) ; print("[NE_Apollyon]KeyDelete"); end , [1293] = function (x) SetServerVariable("[SE_Apollyon]UniqueID",0); print("[SE_Apollyon]KeyDelete"); end , [1294] = function (x) SetServerVariable("[CS_Apollyon]UniqueID",0); print("[CS_Apollyon]KeyDelete"); end , [1295] = function (x) SetServerVariable("[CS_Apollyon_II]UniqueID",0); print("[CS_Apollyon_II]KeyDelete"); end , [1296] = function (x) SetServerVariable("[Central_Apollyon]UniqueID",0); print("[Central_Apollyon]KeyDelete"); end , [1297] = function (x) SetServerVariable("[Central_Apollyon_II]UniqueID",0); print("[Central_Apollyon_II]KeyDelete"); end , [1298] = function (x) SetServerVariable("[Temenos_W_Tower]UniqueID",0); print("[Temenos_W_Tower]KeyDelete"); end , [1299] = function (x) SetServerVariable("[Temenos_N_Tower]UniqueID",0); print("[Temenos_N_Tower]KeyDelete"); end , [1300] = function (x) SetServerVariable("[Temenos_E_Tower]UniqueID",0); print("[Temenos_E_Tower]KeyDelete"); end , [1301] = function (x) SetServerVariable("[C_Temenos_Base]UniqueID",0); print("[C_Temenos_Base]KeyDelete"); end , [1302] = function (x) SetServerVariable("[C_Temenos_Base_II]UniqueID",0); print("[C_Temenos_Base_II]KeyDelete"); end , [1303] = function (x) SetServerVariable("[C_Temenos_1st]UniqueID",0); print("[C_Temenos_1st]KeyDelete"); end , [1304] = function (x) SetServerVariable("[C_Temenos_2nd]UniqueID",0); print("[C_Temenos_2nd]KeyDelete"); end , [1305] = function (x) SetServerVariable("[C_Temenos_3rd]UniqueID",0); print("[C_Temenos_3rd]KeyDelete"); end , [1306] = function (x) SetServerVariable("[C_Temenos_4th]UniqueID",0); print("[C_Temenos_4th]KeyDelete"); end , [1307] = function (x) SetServerVariable("[C_Temenos_4th_II]UniqueID",0); print("[C_Temenos_4th_II]KeyDelete"); end , } end end; function GetInstanceRegion(instanceID) region = 0; for K = 1,table.getn (APPOLLYON_SE_NE_BCNM_LIST),2 do if( APPOLLYON_SE_NE_BCNM_LIST[K] == instanceID)then region =APPOLLYON_SE_NE_BCNM_LIST[K+1][5]; end end for L = 1,table.getn (APPOLLYON_NW_SW_BCNM_LIST),2 do if(APPOLLYON_NW_SW_BCNM_LIST[L] == instanceID)then region =APPOLLYON_NW_SW_BCNM_LIST[L+1][5] ; end end for M = 1,table.getn (TEMENOS_LIST),2 do if(TEMENOS_LIST[M] == instanceID)then region = TEMENOS_LIST[M+1][5]; end end return region; end; function RegisterLimbusInstance(player,instanceID) local playerLimbusKeyID = player:getVar("characterLimbusKey"); local playerLimbusID = player:getVar("LimbusID"); local inst=0; ResetKeyForEmptyLimbus(player,instanceID); -- instancekey will be reset if this instance is empty if(playerLimbusID == 0 )then playerLimbusID = instanceID; end -- print("Player_:_instanceID_"..playerLimbusID.." Playerkey "..playerLimbusKeyID); if(playerLimbusID~=0)then if(GetLimbusKeyFromInstance(playerLimbusID)==0 and playerLimbusKeyID==0)then inst = player:bcnmRegister(playerLimbusID); -- Build Limbus printf("Regionfound: %u",inst); if(inst == GetInstanceRegion(playerLimbusID))then player:bcnmEnter(playerLimbusID); printf("BCNM_CREATE_WITH_REGION: %u",inst); else if(playerLimbusID== 1290 or playerLimbusID== 1291 or playerLimbusID== 1294 or playerLimbusID== 1295 or playerLimbusID== 1296 or playerLimbusID== 1297)then player:setPos(-668,0.1,-666); else player:setPos(643,0.1,-600); end player:messageSpecial(7006); ResetPlayerLimbusVariable(player); print("BCNM_cant_be _created"); end end end end; function TryTobackOnCurrentLimbus(player) local currentlimbus=0; local playerLimbusID = player:getVar("LimbusID"); local playerLimbusKeyID = player:getVar("characterLimbusKey"); -- print("Player_:_instanceID_"..playerLimbusID.." Playerkey "..playerLimbusKeyID); if( GetLimbusKeyFromInstance(playerLimbusID) == playerLimbusKeyID and player:isSpecialBattlefieldEmpty(GetInstanceRegion(playerLimbusID))==1 )then -- player deco and back currentlimbus=playerLimbusID; print("trying_to_add_player_on_the_current_bcnm"); local registration = player:addPlayerToSpecialBattlefield(playerLimbusID); if(registration ~= 1)then currentlimbus=0; end else currentlimbus=0; end return currentlimbus; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Balakaf.lua
37
1031
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Balakaf -- Type: Standard NPC -- @pos 25.505 -6.999 126.478 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0203); 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
kitala1/darkstar
scripts/globals/items/plate_of_dorado_sushi_+1.lua
21
1682
----------------------------------------- -- ID: 5179 -- Item: plate_of_dorado_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 5 -- Accuracy % 16 -- Accuracy Cap 80 -- Ranged ACC % 16 -- Ranged ACC Cap 80 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5179); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_ENMITY, 3); target:addMod(MOD_DEX, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_ACC_CAP, 80); target:addMod(MOD_FOOD_RACCP, 16); target:addMod(MOD_FOOD_RACC_CAP, 80); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_ENMITY, 3); target:delMod(MOD_DEX, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_ACC_CAP, 80); target:delMod(MOD_FOOD_RACCP, 16); target:delMod(MOD_FOOD_RACC_CAP, 80); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Norg/npcs/HomePoint#2.lua
12
1166
----------------------------------- -- Area: Norg -- NPC: HomePoint#2 -- @pos -65 -5 54 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Norg/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 104); 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 == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
brltty/brltty
brltty-prologue.lua
1
1764
--[[ libbrlapi - A library providing access to braille terminals for applications. Copyright (C) 2006-2022 by Dave Mielke <dave@mielke.cc> libbrlapi comes with ABSOLUTELY NO WARRANTY. This is free software, placed under the terms of the GNU Lesser General Public License, as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Please see the file LICENSE-LGPL for details. Web Page: http://brltty.app/ This software is maintained by Dave Mielke <dave@mielke.cc>. ]] programName = string.match(arg[0], "([^/]*)$") programArgumentCount = #arg programArgumentNumber = 1 function writeProgramMessage (message) io.stderr:write(string.format("%s: %s\n", programName, message)) end function syntaxError (message) writeProgramMessage(message) os.exit(2) end function haveMoreProgramArguments () return programArgumentNumber <= programArgumentCount end function nextProgramArgument (label) if not haveMoreProgramArguments() then syntaxError(string.format("missing %s", label)) end local argument = arg[programArgumentNumber] programArgumentNumber = programArgumentNumber + 1 return argument end function stringContains (string, substring) return not not string:find(substring, 1, true) end function splitString (string, delimiter) local components = {} local count = 0 local oldPosition = 1 while true do local newPosition = string:find(delimiter, oldPosition, true) if not newPosition then break end count = count + 1 components[count] = string:sub(oldPosition, newPosition-1) oldPosition = newPosition + #delimiter end count = count + 1 components[count] = string:sub(oldPosition) return components end
lgpl-2.1
ominux/torch7
test/test.lua
9
92766
--require 'torch' local mytester local torchtest = {} local msize = 100 local precision -- Lua 5.2 compatibility local loadstring = loadstring or load local unpack = unpack or table.unpack local function maxdiff(x,y) local d = x-y if x:type() == 'torch.DoubleTensor' or x:type() == 'torch.FloatTensor' then return d:abs():max() else local dd = torch.Tensor():resize(d:size()):copy(d) return dd:abs():max() end end function torchtest.dot() local types = { ['torch.DoubleTensor'] = 1e-8, -- for ddot ['torch.FloatTensor'] = 1e-4, -- for sdot } for tname, prec in pairs(types) do local v1 = torch.randn(100):type(tname) local v2 = torch.randn(100):type(tname) local res1 = torch.dot(v1,v2) local res2 = 0 for i = 1,v1:size(1) do res2 = res2 + v1[i] * v2[i] end local err = math.abs(res1-res2) mytester:assertlt(err, prec, 'error in torch.dot (' .. tname .. ')') end end local genericSingleOpTest = [[ -- [res] torch.functionname([res,] x) -- contiguous local m1 = torch.randn(100,100) local res1 = torch.functionname(m1[{ 4,{} }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.functionname(m1[4][i]) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerrc = 0 for i = 1, err:size(1) do if err[i] > maxerrc then maxerrc = err[i] end end -- non-contiguous local m1 = torch.randn(100,100) local res1 = torch.functionname(m1[{ {}, 4 }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.functionname(m1[i][4]) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerrnc = 0 for i = 1, err:size(1) do if err[i] > maxerrnc then maxerrnc = err[i] end end return maxerrc, maxerrnc ]] function torchtest.sin() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sin')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.sinh() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sinh')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.asin() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'asin')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.cos() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'cos')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.cosh() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'cosh')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.acos() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'acos')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.tan() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'tan')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.tanh() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'tanh')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.atan() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'atan')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.log() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'log')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.sqrt() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sqrt')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.exp() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'exp')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.floor() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'floor')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.ceil() local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'ceil')) local maxerrc, maxerrnc = f() mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous') mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous') end function torchtest.round() -- [res] torch.round([res,] x) -- contiguous local m1 = torch.randn(100,100) local res1 = torch.round(m1[{ 4,{} }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.floor(m1[4][i]+0.5) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerrc = 0 for i = 1, err:size(1) do if err[i] > maxerrc then maxerrc = err[i] end end mytester:assertlt(maxerrc, precision, 'error in torch.round - contiguous') -- non-contiguous local m1 = torch.randn(100,100) local res1 = torch.round(m1[{ {}, 4 }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.floor(m1[i][4]+0.5) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerrnc = 0 for i = 1, err:size(1) do if err[i] > maxerrnc then maxerrnc = err[i] end end mytester:assertlt(maxerrnc, precision, 'error in torch.round - non-contiguous') end function torchtest.max() -- torch.max([resval, resind,] x [,dim]) -- torch.max( x ) -- contiguous local m1 = torch.randn(100,100) local res1 = torch.max(m1) local res2 = m1[1][1] for i = 1,m1:size(1) do for j = 1,m1:size(2) do if m1[i][j] > res2 then res2 = m1[i][j] end end end local err = res1 - res2 mytester:assertlt(err, precision, 'error in torch.max - contiguous') -- non-contiguous local m1 = torch.randn(10,10,10) local m2 = m1[{{}, 4, {}}] local res1 = torch.max(m2) local res2 = m2[1][1] for i = 1,m2:size(1) do for j = 1,m2:size(2) do if m2[i][j] > res2 then res2 = m2[i][j] end end end local err = res1 - res2 mytester:assertlt(err, precision, 'error in torch.max - non-contiguous') -- torch.max([resval, resind,] x ,dim]) local m1 = torch.randn(100,100) local res1val, res1ind = torch.max(m1, 2) local res2val = res1val:clone():zero() local res2ind = res1ind:clone():zero() for i=1, m1:size(1) do res2val[i] = m1[i][1] res2ind[i] = 1 for j=1, m1:size(2) do if m1[i][j] > res2val[i][1] then res2val[i] = m1[i][j] res2ind[i] = j end end end local errval = res1val:clone():zero() for i = 1, res1val:size(1) do errval[i] = math.abs(res1val[i][1] - res2val[i][1]) mytester:asserteq(res1ind[i][1], res2ind[i][1], 'error in torch.max - non-contiguous') end local maxerr = 0 for i = 1, errval:size(1) do if errval[i][1] > maxerr then maxerr = errval[i] end end mytester:assertlt(maxerr, precision, 'error in torch.max - non-contiguous') -- NaNs for index in pairs{1, 5, 100} do local m1 = torch.randn(100) m1[index] = 0/0 local res1val, res1ind = torch.max(m1, 1) mytester:assert(res1val[1] ~= res1val[1], 'error in torch.max (value) - NaNs') mytester:assert(res1ind[1] == index, 'error in torch.max (index) - NaNs') local res1val = torch.max(m1) mytester:assert(res1val ~= res1val, 'error in torch.max - NaNs') end end function torchtest.min() -- torch.min([resval, resind,] x [,dim]) -- torch.min( x ) -- contiguous local m1 = torch.randn(100,100) local res1 = torch.min(m1) local res2 = m1[1][1] for i = 1,m1:size(1) do for j = 1,m1:size(2) do if m1[i][j] < res2 then res2 = m1[i][j] end end end local err = res1 - res2 mytester:assertlt(err, precision, 'error in torch.min - contiguous') -- non-contiguous local m1 = torch.randn(10,10,10) local m2 = m1[{{}, 4, {}}] local res1 = torch.min(m2) local res2 = m2[1][1] for i = 1,m2:size(1) do for j = 1,m2:size(2) do if m2[i][j] < res2 then res2 = m2[i][j] end end end local err = res1 - res2 mytester:assertlt(err, precision, 'error in torch.min - non-contiguous') -- torch.min([resval, resind,] x ,dim]) local m1 = torch.randn(100,100) local res1val, res1ind = torch.min(m1, 2) local res2val = res1val:clone():zero() local res2ind = res1ind:clone():zero() for i=1, m1:size(1) do res2val[i] = m1[i][1] res2ind[i] = 1 for j=1, m1:size(2) do if m1[i][j] < res2val[i][1] then res2val[i] = m1[i][j] res2ind[i] = j end end end local errval = res1val:clone():zero() for i = 1, res1val:size(1) do errval[i] = math.abs(res1val[i][1] - res2val[i][1]) mytester:asserteq(res1ind[i][1], res2ind[i][1], 'error in torch.min - non-contiguous') end local minerr = 0 for i = 1, errval:size(1) do if errval[i][1] < minerr then minerr = errval[i] end end mytester:assertlt(minerr, precision, 'error in torch.min - non-contiguous') -- NaNs for index in pairs{1, 5, 100} do local m1 = torch.randn(100) m1[index] = 0/0 local res1val, res1ind = torch.min(m1, 1) mytester:assert(res1val[1] ~= res1val[1], 'error in torch.min (value) - NaNs') mytester:assert(res1ind[1] == index, 'error in torch.min (index) - NaNs') local res1val = torch.min(m1) mytester:assert(res1val ~= res1val, 'error in torch.min - NaNs') end end function torchtest.cmax() -- Two tensors. local a = torch.rand(msize, msize) local b = torch.rand(msize, msize) local c = torch.cmax(a, b) local expected_c = torch.zeros(msize, msize) expected_c:map2(a, b, function(_, a, b) return math.max(a, b) end) mytester:assertTensorEq(expected_c, c, 0, 'error in torch.cmax(tensor, tensor)') -- Tensor and scalar. local v = torch.uniform() c = torch.cmax(a, v) expected_c:map(a, function(_, a) return math.max(a, v) end) mytester:assertTensorEq(expected_c, c, 0, 'error in torch.cmax(tensor, scalar).') end function torchtest.cmin() -- Two tensors. local a = torch.rand(msize, msize) local b = torch.rand(msize, msize) local c = torch.cmin(a, b) local expected_c = torch.zeros(msize, msize) expected_c:map2(a, b, function(_, a, b) return math.min(a, b) end) mytester:assertTensorEq(expected_c, c, 0, 'error in torch.cmin(tensor, tensor)') -- Tensor and scalar. local v = torch.uniform() c = torch.cmin(a, v) expected_c:map(a, function(_, a) return math.min(a, v) end) mytester:assertTensorEq(expected_c, c, 0, 'error in torch.cmin(tensor, scalar).') end for i, v in ipairs{{10}, {5, 5}} do torchtest['allAndAny' .. i] = function () local x = torch.ones(unpack(v)):byte() mytester:assert(x:all(), 'error in all()') mytester:assert(x:any(), 'error in any()') x[3] = 0 mytester:assert(not x:all(), 'error in all()') mytester:assert(x:any(), 'error in any()') x:zero() mytester:assert(not x:all(), 'error in all()') mytester:assert(not x:any(), 'error in any()') end end function torchtest.mv() local m1 = torch.randn(100,100) local v1 = torch.randn(100) local res1 = torch.mv(m1,v1) local res2 = res1:clone():zero() for i = 1,m1:size(1) do for j = 1,m1:size(2) do res2[i] = res2[i] + m1[i][j] * v1[j] end end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.mv') end function torchtest.add() -- [res] torch.add([res,] tensor1, tensor2) local m1 = torch.randn(100,100) local v1 = torch.randn(100) local res1 = torch.add(m1[{ 4,{} }],v1) local res2 = res1:clone():zero() for i = 1,m1:size(2) do res2[i] = m1[4][i] + v1[i] end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.add - contiguous') local m1 = torch.randn(100,100) local v1 = torch.randn(100) local res1 = torch.add(m1[{ {},4 }],v1) local res2 = res1:clone():zero() for i = 1,m1:size(1) do res2[i] = m1[i][4] + v1[i] end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.add - non contiguous') -- [res] torch.add([res,] tensor, value) local m1 = torch.randn(10,10) local res1 = m1:clone() res1[{ 3,{} }]:add(2) local res2 = m1:clone() for i = 1,m1:size(1) do res2[{ 3,i }] = res2[{ 3,i }] + 2 end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.add - scalar, contiguous') local m1 = torch.randn(10,10) local res1 = m1:clone() res1[{ {},3 }]:add(2) local res2 = m1:clone() for i = 1,m1:size(1) do res2[{ i,3 }] = res2[{ i,3 }] + 2 end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.add - scalar, non contiguous') -- [res] torch.add([res,] tensor1, value, tensor2) end function torchtest.mul() local m1 = torch.randn(10,10) local res1 = m1:clone() res1[{ {},3 }]:mul(2) local res2 = m1:clone() for i = 1,m1:size(1) do res2[{ i,3 }] = res2[{ i,3 }] * 2 end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.mul - scalar, non contiguous') end function torchtest.div() local m1 = torch.randn(10,10) local res1 = m1:clone() res1[{ {},3 }]:div(2) local res2 = m1:clone() for i = 1,m1:size(1) do res2[{ i,3 }] = res2[{ i,3 }] / 2 end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.div - scalar, non contiguous') end function torchtest.mm() -- helper function local function matrixmultiply(mat1,mat2) local n = mat1:size(1) local m = mat1:size(2) local p = mat2:size(2) local res = torch.zeros(n,p) for i = 1, n do for j = 1, p do local sum = 0 for k = 1, m do sum = sum + mat1[i][k]*mat2[k][j] end res[i][j] = sum end end return res end -- contiguous case local n, m, p = 10, 10, 5 local mat1 = torch.randn(n,m) local mat2 = torch.randn(m,p) local res = torch.mm(mat1,mat2) local res2 = matrixmultiply(mat1,mat2) mytester:assertTensorEq(res,res2,precision,'error in torch.mm') -- non contiguous case 1 local n, m, p = 10, 10, 5 local mat1 = torch.randn(n,m) local mat2 = torch.randn(p,m):t() local res = torch.mm(mat1,mat2) local res2 = matrixmultiply(mat1,mat2) mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous') -- non contiguous case 2 local n, m, p = 10, 10, 5 local mat1 = torch.randn(m,n):t() local mat2 = torch.randn(m,p) local res = torch.mm(mat1,mat2) local res2 = matrixmultiply(mat1,mat2) mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous') -- non contiguous case 3 local n, m, p = 10, 10, 5 local mat1 = torch.randn(m,n):t() local mat2 = torch.randn(p,m):t() local res = torch.mm(mat1,mat2) local res2 = matrixmultiply(mat1,mat2) mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous') -- test with zero stride local n, m, p = 10, 10, 5 local mat1 = torch.randn(n,m) local mat2 = torch.randn(m,1):expand(m,p) local res = torch.mm(mat1,mat2) local res2 = matrixmultiply(mat1,mat2) mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous, zero stride') end function torchtest.bmm() local num_batches = 10 local M, N, O = 23, 8, 12 local b1 = torch.randn(num_batches, M, N) local b2 = torch.randn(num_batches, N, O) local res = torch.bmm(b1, b2) for i = 1, num_batches do local r = torch.mm(b1[i], b2[i]) mytester:assertTensorEq(r, res[i], precision, 'result matrix ' .. i .. ' wrong') end end function torchtest.addbmm() local num_batches = 10 local M, N, O = 12, 8, 5 local b1 = torch.randn(num_batches, M, N) local b2 = torch.randn(num_batches, N, O) local res = torch.bmm(b1, b2) local res2 = torch.Tensor():resizeAs(res[1]):zero() res2:addbmm(b1,b2) mytester:assertTensorEq(res2, res:sum(1), precision, 'addbmm result wrong') res2:addbmm(1,b1,b2) mytester:assertTensorEq(res2, res:sum(1)*2, precision, 'addbmm result wrong') res2:addbmm(1,res2,.5,b1,b2) mytester:assertTensorEq(res2, res:sum(1)*2.5, precision, 'addbmm result wrong') local res3 = torch.addbmm(1,res2,0,b1,b2) mytester:assertTensorEq(res3, res2, precision, 'addbmm result wrong') local res4 = torch.addbmm(1,res2,.5,b1,b2) mytester:assertTensorEq(res4, res:sum(1)*3, precision, 'addbmm result wrong') local res5 = torch.addbmm(0,res2,1,b1,b2) mytester:assertTensorEq(res5, res:sum(1), precision, 'addbmm result wrong') local res6 = torch.addbmm(.1,res2,.5,b1,b2) mytester:assertTensorEq(res6, res2*.1 + res:sum(1)*.5, precision, 'addbmm result wrong') end function torchtest.baddbmm() local num_batches = 10 local M, N, O = 12, 8, 5 local b1 = torch.randn(num_batches, M, N) local b2 = torch.randn(num_batches, N, O) local res = torch.bmm(b1, b2) local res2 = torch.Tensor():resizeAs(res):zero() res2:baddbmm(b1,b2) mytester:assertTensorEq(res2, res, precision, 'baddbmm result wrong') res2:baddbmm(1,b1,b2) mytester:assertTensorEq(res2, res*2, precision, 'baddbmm result wrong') res2:baddbmm(1,res2,.5,b1,b2) mytester:assertTensorEq(res2, res*2.5, precision, 'baddbmm result wrong') local res3 = torch.baddbmm(1,res2,0,b1,b2) mytester:assertTensorEq(res3, res2, precision, 'baddbmm result wrong') local res4 = torch.baddbmm(1,res2,.5,b1,b2) mytester:assertTensorEq(res4, res*3, precision, 'baddbmm result wrong') local res5 = torch.baddbmm(0,res2,1,b1,b2) mytester:assertTensorEq(res5, res, precision, 'baddbmm result wrong') local res6 = torch.baddbmm(.1,res2,.5,b1,b2) mytester:assertTensorEq(res6, res2*.1 + res*.5, precision, 'baddbmm result wrong') end function torchtest.clamp() local m1 = torch.rand(100):mul(5):add(-2.5) -- uniform in [-2.5, 2.5] -- just in case we're extremely lucky: local min_val = -1 local max_val = 1 m1[1] = min_val m1[2] = max_val local res1 = m1:clone() res1:clamp(min_val, max_val) local res2 = m1:clone() for i = 1,m1:size(1) do if res2[i] > max_val then res2[i] = max_val elseif res2[i] < min_val then res2[i] = min_val end end local err = (res1-res2):abs():max() mytester:assertlt(err, precision, 'error in torch.div - scalar, non contiguous') end function torchtest.pow() -- [res] torch.pow([res,] x) -- base - tensor, exponent - number -- contiguous local m1 = torch.randn(100,100) local res1 = torch.pow(m1[{ 4,{} }], 3) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.pow(m1[4][i], 3) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do if err[i] > maxerr then maxerr = err[i] end end mytester:assertlt(maxerr, precision, 'error in torch.pow - contiguous') -- non-contiguous local m1 = torch.randn(100,100) local res1 = torch.pow(m1[{ {}, 4 }], 3) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.pow(m1[i][4], 3) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do if err[i] > maxerr then maxerr = err[i] end end mytester:assertlt(maxerr, precision, 'error in torch.pow - non-contiguous') -- base - number, exponent - tensor -- contiguous local m1 = torch.randn(100,100) local res1 = torch.pow(3, m1[{ 4,{} }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.pow(3, m1[4][i]) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do if err[i] > maxerr then maxerr = err[i] end end mytester:assertlt(maxerr, precision, 'error in torch.pow - contiguous') -- non-contiguous local m1 = torch.randn(100,100) local res1 = torch.pow(3, m1[{ {}, 4 }]) local res2 = res1:clone():zero() for i = 1,res1:size(1) do res2[i] = math.pow(3, m1[i][4]) end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do err[i] = math.abs(res1[i] - res2[i]) end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do if err[i] > maxerr then maxerr = err[i] end end mytester:assertlt(maxerr, precision, 'error in torch.pow - non-contiguous') end function torchtest.cdiv() -- [res] torch.cdiv([res,] tensor1, tensor2) -- contiguous local m1 = torch.randn(10, 10, 10) local m2 = torch.randn(10, 10 * 10) local sm1 = m1[{4, {}, {}}] local sm2 = m2[{4, {}}] local res1 = torch.cdiv(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = sm1[i][j] / sm2[idx1d] end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cdiv - contiguous') -- non-contiguous local m1 = torch.randn(10, 10, 10) local m2 = torch.randn(10 * 10, 10 * 10) local sm1 = m1[{{}, 4, {}}] local sm2 = m2[{{}, 4}] local res1 = torch.cdiv(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = sm1[i][j] / sm2[idx1d] end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cdiv - non-contiguous') end function torchtest.cmul() -- [res] torch.cmul([res,] tensor1, tensor2) -- contiguous local m1 = torch.randn(10, 10, 10) local m2 = torch.randn(10, 10 * 10) local sm1 = m1[{4, {}, {}}] local sm2 = m2[{4, {}}] local res1 = torch.cmul(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = sm1[i][j] * sm2[idx1d] end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cmul - contiguous') -- non-contiguous local m1 = torch.randn(10, 10, 10) local m2 = torch.randn(10 * 10, 10 * 10) local sm1 = m1[{{}, 4, {}}] local sm2 = m2[{{}, 4}] local res1 = torch.cmul(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = sm1[i][j] * sm2[idx1d] end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cmul - non-contiguous') end function torchtest.cpow() -- [res] torch.cpow([res,] tensor1, tensor2) -- contiguous local m1 = torch.rand(10, 10, 10) local m2 = torch.rand(10, 10 * 10) local sm1 = m1[{4, {}, {}}] local sm2 = m2[{4, {}}] local res1 = torch.cpow(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = math.pow(sm1[i][j], sm2[idx1d]) end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cpow - contiguous') -- non-contiguous local m1 = torch.rand(10, 10, 10) local m2 = torch.rand(10 * 10, 10 * 10) local sm1 = m1[{{}, 4, {}}] local sm2 = m2[{{}, 4}] local res1 = torch.cpow(sm1, sm2) local res2 = res1:clone():zero() for i = 1,sm1:size(1) do for j = 1, sm1:size(2) do local idx1d = (((i-1)*sm1:size(1)))+j res2[i][j] = math.pow(sm1[i][j],sm2[idx1d]) end end local err = res1:clone():zero() -- find absolute error for i = 1, res1:size(1) do for j = 1, res1:size(2) do err[i][j] = math.abs(res1[i][j] - res2[i][j]) end end -- find maximum element of error local maxerr = 0 for i = 1, err:size(1) do for j = 1, err:size(2) do if err[i][j] > maxerr then maxerr = err[i][j] end end end mytester:assertlt(maxerr, precision, 'error in torch.cpow - non-contiguous') end function torchtest.sum() local x = torch.rand(msize,msize) local mx = torch.sum(x,2) local mxx = torch.Tensor() torch.sum(mxx,x,2) mytester:asserteq(maxdiff(mx,mxx),0,'torch.sum value') end function torchtest.prod() local x = torch.rand(msize,msize) local mx = torch.prod(x,2) local mxx = torch.Tensor() torch.prod(mxx,x,2) mytester:asserteq(maxdiff(mx,mxx),0,'torch.prod value') end function torchtest.cumsum() local x = torch.rand(msize,msize) local mx = torch.cumsum(x,2) local mxx = torch.Tensor() torch.cumsum(mxx,x,2) mytester:asserteq(maxdiff(mx,mxx),0,'torch.cumsum value') end function torchtest.cumprod() local x = torch.rand(msize,msize) local mx = torch.cumprod(x,2) local mxx = torch.Tensor() torch.cumprod(mxx,x,2) mytester:asserteq(maxdiff(mx,mxx),0,'torch.cumprod value') end function torchtest.cross() local x = torch.rand(msize,3,msize) local y = torch.rand(msize,3,msize) local mx = torch.cross(x,y) local mxx = torch.Tensor() torch.cross(mxx,x,y) mytester:asserteq(maxdiff(mx,mxx),0,'torch.cross value') end function torchtest.zeros() local mx = torch.zeros(msize,msize) local mxx = torch.Tensor() torch.zeros(mxx,msize,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.zeros value') end function torchtest.histc() local x = torch.Tensor{ 2, 4, 2, 2, 5, 4 } local y = torch.histc(x, 5, 1, 5) -- nbins, min, max local z = torch.Tensor{ 0, 3, 0, 2, 1 } mytester:assertTensorEq(y,z,precision,'error in torch.histc') end function torchtest.ones() local mx = torch.ones(msize,msize) local mxx = torch.Tensor() torch.ones(mxx,msize,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.ones value') end function torchtest.diag() local x = torch.rand(msize,msize) local mx = torch.diag(x) local mxx = torch.Tensor() torch.diag(mxx,x) mytester:asserteq(maxdiff(mx,mxx),0,'torch.diag value') end function torchtest.eye() local mx = torch.eye(msize,msize) local mxx = torch.Tensor() torch.eye(mxx,msize,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.eye value') end function torchtest.renorm() local m1 = torch.randn(10,5) local res1 = torch.Tensor() local m2 local function renorm(matrix, value, dim, max_norm) local m1 = matrix:transpose(dim, 1):contiguous() -- collapse non-dim dimensions: m2 = m1:reshape(m1:size(1), m1:nElement()/m1:size(1)) local norms = m2:norm(value,2) -- clip local new_norms = norms:clone() new_norms[torch.gt(norms, max_norm)] = max_norm new_norms:cdiv(norms:add(1e-7)) -- renormalize m1:cmul(new_norms:expandAs(m1)) return m1:transpose(dim, 1) end -- note that the axis fed to torch.renorm is different (2~=1) local maxnorm = m1:norm(2,1):mean() m2 = renorm(m1,2,2,maxnorm) m1:renorm(2,2,maxnorm) mytester:assertTensorEq(m1, m2, 0.00001, 'error in renorm') mytester:assertTensorEq(m1:norm(2,1), m2:norm(2,1), 0.00001, 'error in renorm') m1 = torch.randn(3,4,5) m2 = m1:transpose(2,3):contiguous():reshape(15,4) maxnorm = m2:norm(2,1):mean() m2 = renorm(m2,2,2,maxnorm) m1:renorm(2,2,maxnorm) local m3 = m1:transpose(2,3):contiguous():reshape(15,4) mytester:assertTensorEq(m3, m2, 0.00001, 'error in renorm') mytester:assertTensorEq(m3:norm(2,1), m2:norm(2,1), 0.00001, 'error in renorm') end function torchtest.multinomialwithreplacement() local n_row = 3 for n_col=4,5 do local t=os.time() torch.manualSeed(t) local prob_dist = torch.rand(n_row,n_col) prob_dist:select(2,n_col):fill(0) --index n_col shouldn't be sampled local n_sample = n_col local sample_indices = torch.multinomial(prob_dist, n_sample, true) mytester:assert(prob_dist:dim() == 2, "wrong number of prob_dist dimensions") mytester:assert(sample_indices:size(2) == n_sample, "wrong number of samples") for i=1,n_row do for j=1,n_sample do mytester:assert(sample_indices[{i,j}] ~= n_col, "sampled an index with zero probability") end end end end function torchtest.multinomialwithoutreplacement() local n_row = 3 for n_col=4,5 do local t=os.time() torch.manualSeed(t) local prob_dist = torch.rand(n_row,n_col) prob_dist:select(2,n_col):fill(0) --index n_col shouldn't be sampled local n_sample = 3 local sample_indices = torch.multinomial(prob_dist, n_sample, false) mytester:assert(prob_dist:dim() == 2, "wrong number of prob_dist dimensions") mytester:assert(sample_indices:size(2) == n_sample, "wrong number of samples") for i=1,n_row do local row_samples = {} for j=1,n_sample do local sample_idx = sample_indices[{i,j}] mytester:assert( sample_idx ~= n_col, "sampled an index with zero probability" ) mytester:assert( not row_samples[sample_idx], "sampled an index twice" ) row_samples[sample_idx] = true end end end end function torchtest.multinomialvector() local n_col = 4 local t=os.time() torch.manualSeed(t) local prob_dist = torch.rand(n_col) local n_sample = n_col local sample_indices = torch.multinomial(prob_dist, n_sample, true) local s_dim = sample_indices:dim() mytester:assert(s_dim == 1, "wrong number of returned dimensions: "..s_dim) mytester:assert(prob_dist:dim() == 1, "wrong number of prob_dist dimensions") mytester:assert(sample_indices:size(1) == n_sample, "wrong number of samples") end function torchtest.range() local mx = torch.range(0,1) local mxx = torch.Tensor() torch.range(mxx,0,1) mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value') end function torchtest.rangenegative() local mx = torch.Tensor({1,0}) local mxx = torch.Tensor() torch.range(mxx,1,0,-1) mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for negative step') end function torchtest.rangeequalbounds() local mx = torch.Tensor({1}) local mxx = torch.Tensor() torch.range(mxx,1,1,-1) mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for equal bounds step') torch.range(mxx,1,1,1) mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for equal bounds step') end function torchtest.rangefloat() local mx = torch.FloatTensor():range(0.6, 0.9, 0.1) mytester:asserteq(mx:size(1), 4, 'wrong size for FloatTensor range') mx = torch.FloatTensor():range(1, 10, 0.3) mytester:asserteq(mx:size(1), 31, 'wrong size for FloatTensor range') end function torchtest.rangedouble() local mx = torch.DoubleTensor():range(0.6, 0.9, 0.1) mytester:asserteq(mx:size(1), 4, 'wrong size for DoubleTensor range') mx = torch.DoubleTensor():range(1, 10, 0.3) mytester:asserteq(mx:size(1), 31, 'wrong size for DoubleTensor range') end function torchtest.randperm() local t=os.time() torch.manualSeed(t) local mx = torch.randperm(msize) local mxx = torch.Tensor() torch.manualSeed(t) torch.randperm(mxx,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.randperm value') end function torchtest.reshape() local x = torch.rand(10,13,23) local mx = torch.reshape(x,130,23) local mxx = torch.Tensor() torch.reshape(mxx,x,130,23) mytester:asserteq(maxdiff(mx,mxx),0,'torch.reshape value') end local function assertIsOrdered(order, x, mxx, ixx, task) local areOrdered if order == 'descending' then areOrdered = function(a, b) return a >= b end elseif order == 'ascending' then areOrdered = function(a, b) return a <= b end else error('unknown order "' .. order .. '", must be "ascending" or "descending"') end local decreasing = true for j = 1,msize do for k = 2,msize do decreasing = decreasing and areOrdered(mxx[j][k-1], mxx[j][k]) end end mytester:assert(decreasing, 'torch.sort (' .. order .. ') values unordered for ' .. task) local seen = torch.ByteTensor(msize) local indicesCorrect = true for k = 1,msize do seen:zero() for j = 1,msize do indicesCorrect = indicesCorrect and (x[k][ixx[k][j]] == mxx[k][j]) seen[ixx[k][j]] = 1 end indicesCorrect = indicesCorrect and (torch.sum(seen) == msize) end mytester:assert(indicesCorrect, 'torch.sort (' .. order .. ') indices wrong for ' .. task) end function torchtest.sortAscending() local x = torch.rand(msize,msize) local mx,ix = torch.sort(x) -- Test use of result tensor local mxx = torch.Tensor() local ixx = torch.LongTensor() torch.sort(mxx,ixx,x) mytester:asserteq(maxdiff(mx,mxx),0,'torch.sort (ascending) value') mytester:asserteq(maxdiff(ix,ixx),0,'torch.sort (ascending) index') -- Test sorting of random numbers assertIsOrdered('ascending', x, mxx, ixx, 'random') mytester:assertTensorEq( torch.sort(torch.Tensor{ 50, 40, 30, 20, 10 }), torch.Tensor{ 10, 20, 30, 40, 50 }, 1e-16, "torch.sort (ascending) simple sort" ) -- Test that we still have proper sorting with duplicate keys local x = torch.floor(torch.rand(msize,msize)*10) torch.sort(mxx,ixx,x) assertIsOrdered('ascending', x, mxx, ixx, 'random with duplicate keys') end function torchtest.sortDescending() local x = torch.rand(msize,msize) local mx,ix = torch.sort(x,true) -- Test use of result tensor local mxx = torch.Tensor() local ixx = torch.LongTensor() torch.sort(mxx,ixx,x,true) mytester:asserteq(maxdiff(mx,mxx),0,'torch.sort (descending) value') mytester:asserteq(maxdiff(ix,ixx),0,'torch.sort (descending) index') -- Test sorting of random numbers assertIsOrdered('descending', x, mxx, ixx, 'random') -- Test simple sort task mytester:assertTensorEq( torch.sort(torch.Tensor{ 10, 20, 30, 40, 50 },true), torch.Tensor{ 50, 40, 30, 20, 10 }, 1e-16, "torch.sort (descending) simple sort" ) -- Test that we still have proper sorting with duplicate keys assertIsOrdered('descending', x, mxx, ixx, 'random with duplicate keys') end function torchtest.kthvalue() local x = torch.rand(msize, msize, msize) local x0 = x:clone() do local k = math.random(1, msize) local mx, ix = torch.kthvalue(x, k) local mxx, ixx = torch.sort(x) mytester:assertTensorEq(mxx:select(3, k), mx, 0, 'torch.kthvalue value') mytester:assertTensorEq(ixx:select(3, k), ix, 0, 'torch.kthvalue index') end do -- test use of result tensors local k = math.random(1, msize) local mx = torch.Tensor() local ix = torch.LongTensor() torch.kthvalue(mx, ix, x, k) local mxx, ixx = torch.sort(x) mytester:assertTensorEq(mxx:select(3, k), mx, 0, 'torch.kthvalue value') mytester:assertTensorEq(ixx:select(3, k), ix, 0, 'torch.kthvalue index') end do -- test non-default dim local k = math.random(1, msize) local mx, ix = torch.kthvalue(x, k, 1) local mxx, ixx = torch.sort(x, 1) mytester:assertTensorEq(mxx:select(1, k), mx, 0, 'torch.kthvalue value') mytester:assertTensorEq(ixx:select(1, k), ix, 0, 'torch.kthvalue index') end do -- non-contiguous local y = x:narrow(2, 1, 1) local y0 = y:clone() local k = math.random(1, msize) local my, ix = torch.kthvalue(y, k) local my0, ix0 = torch.kthvalue(y0, k) mytester:assertTensorEq(my, my0, 0, 'torch.kthvalue value') mytester:assertTensorEq(ix, ix0, 0, 'torch.kthvalue index') end mytester:assertTensorEq(x, x0, 0, 'torch.kthvalue modified input') -- simple test case (with repetitions) local y = torch.Tensor{3,5,4,1,1,5} mytester:assertTensorEq(torch.kthvalue(y, 3), torch.Tensor{3}, 1e-16, 'torch.kthvalue simple') mytester:assertTensorEq(torch.kthvalue(y, 2), torch.Tensor{1}, 1e-16, 'torch.kthvalue simple') end function torchtest.median() for _, msize in ipairs{155,156} do local x = torch.rand(msize, msize) local x0 = x:clone() local mx, ix = torch.median(x) local mxx, ixx = torch.sort(x) local ind = math.floor((msize+1)/2) mytester:assertTensorEq(mxx:select(2, ind), mx, 0, 'torch.median value') mytester:assertTensorEq(ixx:select(2, ind), ix, 0, 'torch.median index') -- Test use of result tensor local mr = torch.Tensor() local ir = torch.LongTensor() torch.median(mr, ir, x) mytester:assertTensorEq(mr, mx, 0, 'torch.median result tensor value') mytester:assertTensorEq(ir, ix, 0, 'torch.median result tensor index') -- Test non-default dim mx, ix = torch.median(x, 1) mxx, ixx = torch.sort(x, 1) mytester:assertTensorEq(mxx:select(1, ind), mx, 0,'torch.median value') mytester:assertTensorEq(ixx:select(1, ind), ix, 0,'torch.median index') -- input unchanged mytester:assertTensorEq(x, x0, 0, 'torch.median modified input') end end function torchtest.tril() local x = torch.rand(msize,msize) local mx = torch.tril(x) local mxx = torch.Tensor() torch.tril(mxx,x) mytester:asserteq(maxdiff(mx,mxx),0,'torch.tril value') end function torchtest.triu() local x = torch.rand(msize,msize) local mx = torch.triu(x) local mxx = torch.Tensor() torch.triu(mxx,x) mytester:asserteq(maxdiff(mx,mxx),0,'torch.tril value') end function torchtest.cat() local x = torch.rand(13,msize,msize) local y = torch.rand(17,msize,msize) local mx = torch.cat(x,y,1) local mxx = torch.Tensor() torch.cat(mxx,x,y,1) mytester:asserteq(maxdiff(mx,mxx),0,'torch.cat value') end function torchtest.sin() local x = torch.rand(msize,msize,msize) local mx = torch.sin(x) local mxx = torch.Tensor() torch.sin(mxx,x) mytester:asserteq(maxdiff(mx,mxx),0,'torch.sin value') end function torchtest.linspace() local from = math.random() local to = from+math.random() local mx = torch.linspace(from,to,137) local mxx = torch.Tensor() torch.linspace(mxx,from,to,137) mytester:asserteq(maxdiff(mx,mxx),0,'torch.linspace value') mytester:assertError(function() torch.linspace(0,1,1) end, 'accepted 1 point between 2 distinct endpoints') mytester:assertTensorEq(torch.linspace(0,0,1),torch.zeros(1),1e-16, 'failed to generate for torch.linspace(0,0,1)') end function torchtest.logspace() local from = math.random() local to = from+math.random() local mx = torch.logspace(from,to,137) local mxx = torch.Tensor() torch.logspace(mxx,from,to,137) mytester:asserteq(maxdiff(mx,mxx),0,'torch.logspace value') mytester:assertError(function() torch.logspace(0,1,1) end, 'accepted 1 point between 2 distinct endpoints') mytester:assertTensorEq(torch.logspace(0,0,1),torch.ones(1),1e-16, 'failed to generate for torch.linspace(0,0,1)') end function torchtest.rand() torch.manualSeed(123456) local mx = torch.rand(msize,msize) local mxx = torch.Tensor() torch.manualSeed(123456) torch.rand(mxx,msize,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.rand value') end function torchtest.randn() torch.manualSeed(123456) local mx = torch.randn(msize,msize) local mxx = torch.Tensor() torch.manualSeed(123456) torch.randn(mxx,msize,msize) mytester:asserteq(maxdiff(mx,mxx),0,'torch.randn value') end function torchtest.gesv() if not torch.gesv then return end local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23}, {-6.05, -3.30, 5.36, -4.44, 1.08}, {-0.45, 2.58, -2.70, 0.27, 9.04}, {8.32, 2.71, 4.35, -7.17, 2.14}, {-9.67, -5.14, -7.26, 6.08, -6.87}}):t() local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03}, {-1.56, 4.00, -8.67, 1.75, 2.86}, {9.81, -4.09, -4.57, -8.61, 8.99}}):t() local mx = torch.gesv(b,a) mytester:assertlt(b:dist(a*mx),1e-12,'torch.gesv') local ta = torch.Tensor() local tb = torch.Tensor() local mxx = torch.gesv(tb,ta,b,a) local mxxx = torch.gesv(b,a,b,a) mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value temp') mytester:asserteq(maxdiff(mx,b),0,'torch.gesv value flag') mytester:asserteq(maxdiff(mx,mxx),0,'torch.gesv value out1') mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gesv value out2') end function torchtest.gesv_reuse() if not torch.gesv then return end local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23}, {-6.05, -3.30, 5.36, -4.44, 1.08}, {-0.45, 2.58, -2.70, 0.27, 9.04}, {8.32, 2.71, 4.35, -7.17, 2.14}, {-9.67, -5.14, -7.26, 6.08, -6.87}}):t() local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03}, {-1.56, 4.00, -8.67, 1.75, 2.86}, {9.81, -4.09, -4.57, -8.61, 8.99}}):t() local mx = torch.gesv(b,a) local ta = torch.Tensor() local tb = torch.Tensor() torch.gesv(tb,ta,b,a) mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value temp') torch.gesv(tb,ta,b,a) mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value reuse') end function torchtest.trtrs() if not torch.trtrs then return end local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23}, {-6.05, -3.30, 5.36, -4.44, 1.08}, {-0.45, 2.58, -2.70, 0.27, 9.04}, {8.32, 2.71, 4.35, -7.17, 2.14}, {-9.67, -5.14, -7.26, 6.08, -6.87}}):t() local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03}, {-1.56, 4.00, -8.67, 1.75, 2.86}, {9.81, -4.09, -4.57, -8.61, 8.99}}):t() local U = torch.triu(a) local L = torch.tril(a) -- solve Ux = b local x = torch.trtrs(b, U) mytester:assertlt(b:dist(U*x),1e-12,'torch.trtrs') x = torch.trtrs(b, U, 'U', 'N', 'N') mytester:assertlt(b:dist(U*x),1e-12,'torch.trtrs') -- solve Lx = b x = torch.trtrs(b, L, 'L') mytester:assertlt(b:dist(L*x),1e-12,'torch.trtrs') x = torch.trtrs(b, L, 'L', 'N', 'N') mytester:assertlt(b:dist(L*x),1e-12,'torch.trtrs') -- solve U'x = b x = torch.trtrs(b, U, 'U', 'T') mytester:assertlt(b:dist(U:t()*x),1e-12,'torch.trtrs') x = torch.trtrs(b, U, 'U', 'T', 'N') mytester:assertlt(b:dist(U:t()*x),1e-12,'torch.trtrs') -- solve U'x = b by manual transposition y = torch.trtrs(b, U:t(), 'L', 'N') mytester:assertlt(x:dist(y),1e-12,'torch.trtrs') -- solve L'x = b x = torch.trtrs(b, L, 'L', 'T') mytester:assertlt(b:dist(L:t()*x),1e-12,'torch.trtrs') x = torch.trtrs(b, L, 'L', 'T', 'N') mytester:assertlt(b:dist(L:t()*x),1e-12,'torch.trtrs') -- solve L'x = b by manual transposition y = torch.trtrs(b, L:t(), 'U', 'N') mytester:assertlt(x:dist(y),1e-12,'torch.trtrs') end function torchtest.trtrs_reuse() if not torch.trtrs then return end local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23}, {-6.05, -3.30, 5.36, -4.44, 1.08}, {-0.45, 2.58, -2.70, 0.27, 9.04}, {8.32, 2.71, 4.35, -7.17, 2.14}, {-9.67, -5.14, -7.26, 6.08, -6.87}}):t() local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03}, {-1.56, 4.00, -8.67, 1.75, 2.86}, {9.81, -4.09, -4.57, -8.61, 8.99}}):t() local mx = torch.trtrs(b,a) local ta = torch.Tensor() local tb = torch.Tensor() torch.trtrs(tb,ta,b,a) mytester:asserteq(maxdiff(mx,tb),0,'torch.trtrs value temp') tb:zero() torch.trtrs(tb,ta,b,a) mytester:asserteq(maxdiff(mx,tb),0,'torch.trtrs value reuse') end function torchtest.gels_uniquely_determined() if not torch.gels then return end local expectedNorm = 0 local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34}, {-7.84, -0.28, 3.24, 8.09}, {-4.39, -3.24, 6.27, 5.28}, {4.53, 3.83, -6.64, 2.06}}):t() local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28}, {9.35, -4.43, -0.70, -0.26}}):t() local a_copy = a:clone() local b_copy = b:clone() local mx = torch.gels(b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a,mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local ta = torch.Tensor() local tb = torch.Tensor() local mxx = torch.gels(tb,ta,b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local mxxx = torch.gels(b,a,b,a) mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp') mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag') mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1') mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2') end function torchtest.gels_reuse() if not torch.gels then return end local expectedNorm = 0 local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34}, {-7.84, -0.28, 3.24, 8.09}, {-4.39, -3.24, 6.27, 5.28}, {4.53, 3.83, -6.64, 2.06}}):t() local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28}, {9.35, -4.43, -0.70, -0.26}}):t() local ta = torch.Tensor() local tb = torch.Tensor() torch.gels(tb,ta,b,a) mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') torch.gels(tb,ta,b,a) mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') torch.gels(tb,ta,b,a) mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') end function torchtest.gels_overdetermined() if not torch.gels then return end local expectedNorm = 17.390200628863 local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34, 7.08, -5.45}, {-7.84, -0.28, 3.24, 8.09, 2.52, -5.70}, {-4.39, -3.24, 6.27, 5.28, 0.74, -1.19}, {4.53, 3.83, -6.64, 2.06, -2.47, 4.70}}):t() local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28, 5.72, 8.93}, {9.35, -4.43, -0.70, -0.26, -7.36, -2.52}}):t() local a_copy = a:clone() local b_copy = b:clone() local mx = torch.gels(b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a, mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local ta = torch.Tensor() local tb = torch.Tensor() local mxx = torch.gels(tb,ta,b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local mxxx = torch.gels(b,a,b,a) mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp') mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag') mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1') mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2') end function torchtest.gels_underdetermined() if not torch.gels then return end local expectedNorm = 0 local a=torch.Tensor({{ 1.44, -9.96, -7.55}, {-7.84, -0.28, 3.24}, {-4.39, -3.24, 6.27}, {4.53, 3.83, -6.64}}):t() local b=torch.Tensor({{8.58, 8.26, 8.48}, {9.35, -4.43, -0.70}}):t() local a_copy = a:clone() local b_copy = b:clone() local mx = torch.gels(b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a,mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local ta = torch.Tensor() local tb = torch.Tensor() local mxx = torch.gels(tb,ta,b,a) mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a') mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b') mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') local mxxx = torch.gels(b,a,b,a) mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer') mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp') mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag') mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1') mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2') end function torchtest.eig() if not torch.eig then return end local a=torch.Tensor({{ 1.96, 0.00, 0.00, 0.00, 0.00}, {-6.49, 3.80, 0.00, 0.00, 0.00}, {-0.47, -6.39, 4.17, 0.00, 0.00}, {-7.20, 1.50, -1.51, 5.70, 0.00}, {-0.65, -6.34, 2.67, 1.80, -7.10}}):t():clone() local e = torch.eig(a) local ee,vv = torch.eig(a,'V') local te = torch.Tensor() local tv = torch.Tensor() local eee,vvv = torch.eig(te,tv,a,'V') mytester:assertlt(maxdiff(e,ee),1e-12,'torch.eig value') mytester:assertlt(maxdiff(ee,eee),1e-12,'torch.eig value') mytester:assertlt(maxdiff(ee,te),1e-12,'torch.eig value') mytester:assertlt(maxdiff(vv,vvv),1e-12,'torch.eig value') mytester:assertlt(maxdiff(vv,tv),1e-12,'torch.eig value') end function torchtest.eig_reuse() if not torch.eig then return end local X = torch.randn(4,4) X = X:t()*X local e, v = torch.zeros(4,2), torch.zeros(4,4) torch.eig(e, v, X,'V') local Xhat = v * torch.diag(e:select(2,1)) * v:t() mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong') mytester:assert(not v:isContiguous(), 'V is contiguous') torch.eig(e, v, X, 'V') local Xhat = torch.mm(v, torch.mm(e:select(2,1):diag(), v:t())) mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong') mytester:assert(not v:isContiguous(), 'V is contiguous') end function torchtest.eig_noncontig() if not torch.eig then return end local X = torch.randn(4,4) X = X:t()*X local e = torch.zeros(4,2,2)[{ {}, 2, {} }] local v = torch.zeros(4,2,4)[{ {}, 2, {} }] mytester:assert(not v:isContiguous(), 'V is contiguous') mytester:assert(not e:isContiguous(), 'E is contiguous') torch.eig(e, v, X,'V') local Xhat = v * torch.diag(e:select(2,1)) * v:t() mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong') end function torchtest.test_symeig() if not torch.symeig then return end local xval = torch.rand(100,3) local cov = torch.mm(xval:t(), xval) local rese = torch.zeros(3) local resv = torch.zeros(3,3) -- First call to symeig mytester:assert(resv:isContiguous(), 'resv is not contiguous') -- PASS torch.symeig(rese, resv, cov:clone(), 'V') local ahat = resv*torch.diag(rese)*resv:t() mytester:assertTensorEq(cov, ahat, 1e-8, 'VeV\' wrong') -- PASS -- Second call to symeig mytester:assert(not resv:isContiguous(), 'resv is contiguous') -- FAIL torch.symeig(rese, resv, cov:clone(), 'V') local ahat = torch.mm(torch.mm(resv, torch.diag(rese)), resv:t()) mytester:assertTensorEq(cov, ahat, 1e-8, 'VeV\' wrong') -- FAIL end function torchtest.symeig_noncontig() if not torch.symeig then return end local X = torch.rand(5,5) X = X:t()*X local e = torch.zeros(4,2):select(2,2) local v = torch.zeros(4,2,4)[{ {}, 2, {} }] mytester:assert(not v:isContiguous(), 'V is contiguous') mytester:assert(not e:isContiguous(), 'E is contiguous') torch.symeig(e, v, X,'V') local Xhat = v * torch.diag(e) * v:t() mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong') end function torchtest.svd() if not torch.svd then return end local a=torch.Tensor({{8.79, 6.11, -9.15, 9.57, -3.49, 9.84}, {9.93, 6.91, -7.93, 1.64, 4.02, 0.15}, {9.83, 5.04, 4.86, 8.83, 9.80, -8.99}, {5.45, -0.27, 4.85, 0.74, 10.00, -6.02}, {3.16, 7.98, 3.01, 5.80, 4.27, -5.31}}):t():clone() local u,s,v = torch.svd(a) local uu = torch.Tensor() local ss = torch.Tensor() local vv = torch.Tensor() local uuu,sss,vvv = torch.svd(uu,ss,vv,a) mytester:asserteq(maxdiff(u,uu),0,'torch.svd') mytester:asserteq(maxdiff(u,uuu),0,'torch.svd') mytester:asserteq(maxdiff(s,ss),0,'torch.svd') mytester:asserteq(maxdiff(s,sss),0,'torch.svd') mytester:asserteq(maxdiff(v,vv),0,'torch.svd') mytester:asserteq(maxdiff(v,vvv),0,'torch.svd') end function torchtest.svd_reuse() if not torch.svd then return end local X = torch.randn(4,4) local U, S, V = torch.svd(X) local Xhat = torch.mm(U, torch.mm(S:diag(), V:t())) mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong') mytester:assert(not U:isContiguous(), 'U is contiguous') torch.svd(U, S, V, X) local Xhat = torch.mm(U, torch.mm(S:diag(), V:t())) mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong') end function torchtest.svd_noncontig() if not torch.svd then return end local X = torch.randn(5,5) local U = torch.zeros(5,2,5)[{ {}, 2, {} }] local S = torch.zeros(5,2)[{ {}, 2 }] local V = torch.zeros(5,2,5)[{ {}, 2, {} }] mytester:assert(not U:isContiguous(), 'U is contiguous') mytester:assert(not S:isContiguous(), 'S is contiguous') mytester:assert(not V:isContiguous(), 'V is contiguous') torch.svd(U, S, V, X) local Xhat = torch.mm(U, torch.mm(S:diag(), V:t())) mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong') end function torchtest.inverse() if not torch.inverse then return end local M = torch.randn(5,5) local MI = torch.inverse(M) local E = torch.eye(5) mytester:assert(not MI:isContiguous(), 'MI is contiguous') mytester:assertalmosteq(maxdiff(E,torch.mm(M,MI)), 0, 1e-8, 'inverse value') mytester:assertalmosteq(maxdiff(E,torch.mm(MI,M)), 0, 1e-8, 'inverse value') local MII = torch.Tensor(5,5) torch.inverse(MII, M) mytester:assert(not MII:isContiguous(), 'MII is contiguous') mytester:asserteq(maxdiff(MII, MI), 0, 'inverse value in-place') -- second call, now that MII is transposed torch.inverse(MII, M) mytester:assert(not MII:isContiguous(), 'MII is contiguous') mytester:asserteq(maxdiff(MII, MI), 0, 'inverse value in-place') end function torchtest.conv2() local x = torch.rand(math.floor(torch.uniform(50,100)),math.floor(torch.uniform(50,100))) local k = torch.rand(math.floor(torch.uniform(10,20)),math.floor(torch.uniform(10,20))) local imvc = torch.conv2(x,k) local imvc2 = torch.conv2(x,k,'V') local imfc = torch.conv2(x,k,'F') local ki = k:clone(); local ks = k:storage() local kis = ki:storage() for i=ks:size(),1,-1 do kis[ks:size()-i+1]=ks[i] end local imvx = torch.xcorr2(x,ki) local imvx2 = torch.xcorr2(x,ki,'V') local imfx = torch.xcorr2(x,ki,'F') mytester:asserteq(maxdiff(imvc,imvc2),0,'torch.conv2') mytester:asserteq(maxdiff(imvc,imvx),0,'torch.conv2') mytester:asserteq(maxdiff(imvc,imvx2),0,'torch.conv2') mytester:asserteq(maxdiff(imfc,imfx),0,'torch.conv2') mytester:assertlt(math.abs(x:dot(x)-torch.xcorr2(x,x)[1][1]),1e-10,'torch.conv2') local xx = torch.Tensor(2,x:size(1),x:size(2)) xx[1]:copy(x) xx[2]:copy(x) local kk = torch.Tensor(2,k:size(1),k:size(2)) kk[1]:copy(k) kk[2]:copy(k) local immvc = torch.conv2(xx,kk) local immvc2 = torch.conv2(xx,kk,'V') local immfc = torch.conv2(xx,kk,'F') mytester:asserteq(maxdiff(immvc[1],immvc[2]),0,'torch.conv2') mytester:asserteq(maxdiff(immvc[1],imvc),0,'torch.conv2') mytester:asserteq(maxdiff(immvc2[1],imvc2),0,'torch.conv2') mytester:asserteq(maxdiff(immfc[1],immfc[2]),0,'torch.conv2') mytester:asserteq(maxdiff(immfc[1],imfc),0,'torch.conv2') end function torchtest.conv3() local x = torch.rand(math.floor(torch.uniform(20,40)), math.floor(torch.uniform(20,40)), math.floor(torch.uniform(20,40))) local k = torch.rand(math.floor(torch.uniform(5,10)), math.floor(torch.uniform(5,10)), math.floor(torch.uniform(5,10))) local imvc = torch.conv3(x,k) local imvc2 = torch.conv3(x,k,'V') local imfc = torch.conv3(x,k,'F') local ki = k:clone(); local ks = k:storage() local kis = ki:storage() for i=ks:size(),1,-1 do kis[ks:size()-i+1]=ks[i] end local imvx = torch.xcorr3(x,ki) local imvx2 = torch.xcorr3(x,ki,'V') local imfx = torch.xcorr3(x,ki,'F') mytester:asserteq(maxdiff(imvc,imvc2),0,'torch.conv3') mytester:asserteq(maxdiff(imvc,imvx),0,'torch.conv3') mytester:asserteq(maxdiff(imvc,imvx2),0,'torch.conv3') mytester:asserteq(maxdiff(imfc,imfx),0,'torch.conv3') mytester:assertlt(math.abs(x:dot(x)-torch.xcorr3(x,x)[1][1][1]),4*1e-10,'torch.conv3') local xx = torch.Tensor(2,x:size(1),x:size(2),x:size(3)) xx[1]:copy(x) xx[2]:copy(x) local kk = torch.Tensor(2,k:size(1),k:size(2),k:size(3)) kk[1]:copy(k) kk[2]:copy(k) local immvc = torch.conv3(xx,kk) local immvc2 = torch.conv3(xx,kk,'V') local immfc = torch.conv3(xx,kk,'F') mytester:asserteq(maxdiff(immvc[1],immvc[2]),0,'torch.conv3') mytester:asserteq(maxdiff(immvc[1],imvc),0,'torch.conv3') mytester:asserteq(maxdiff(immvc2[1],imvc2),0,'torch.conv3') mytester:asserteq(maxdiff(immfc[1],immfc[2]),0,'torch.conv3') mytester:asserteq(maxdiff(immfc[1],imfc),0,'torch.conv3') end function torchtest.xcorr3_xcorr2_eq() local ix = math.floor(torch.uniform(20,40)) local iy = math.floor(torch.uniform(20,40)) local iz = math.floor(torch.uniform(20,40)) local kx = math.floor(torch.uniform(5,10)) local ky = math.floor(torch.uniform(5,10)) local kz = math.floor(torch.uniform(5,10)) local x = torch.rand(ix,iy,iz) local k = torch.rand(kx,ky,kz) local o3 = torch.xcorr3(x,k) local o32 = torch.zeros(o3:size()) for i=1,o3:size(1) do for j=1,k:size(1) do o32[i]:add(torch.xcorr2(x[i+j-1],k[j])) end end mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq') end function torchtest.fxcorr3_fxcorr2_eq() local ix = math.floor(torch.uniform(20,40)) local iy = math.floor(torch.uniform(20,40)) local iz = math.floor(torch.uniform(20,40)) local kx = math.floor(torch.uniform(5,10)) local ky = math.floor(torch.uniform(5,10)) local kz = math.floor(torch.uniform(5,10)) local x = torch.rand(ix,iy,iz) local k = torch.rand(kx,ky,kz) local o3 = torch.xcorr3(x,k,'F') local o32 = torch.zeros(o3:size()) for i=1,x:size(1) do for j=1,k:size(1) do o32[i+j-1]:add(torch.xcorr2(x[i],k[k:size(1)-j + 1],'F')) end end mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq') end function torchtest.conv3_conv2_eq() local ix = math.floor(torch.uniform(20,40)) local iy = math.floor(torch.uniform(20,40)) local iz = math.floor(torch.uniform(20,40)) local kx = math.floor(torch.uniform(5,10)) local ky = math.floor(torch.uniform(5,10)) local kz = math.floor(torch.uniform(5,10)) local x = torch.rand(ix,iy,iz) local k = torch.rand(kx,ky,kz) local o3 = torch.conv3(x,k) local o32 = torch.zeros(o3:size()) for i=1,o3:size(1) do for j=1,k:size(1) do o32[i]:add(torch.conv2(x[i+j-1],k[k:size(1)-j+1])) end end mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq') end function torchtest.fxcorr3_fxcorr2_eq() local ix = math.floor(torch.uniform(20,40)) local iy = math.floor(torch.uniform(20,40)) local iz = math.floor(torch.uniform(20,40)) local kx = math.floor(torch.uniform(5,10)) local ky = math.floor(torch.uniform(5,10)) local kz = math.floor(torch.uniform(5,10)) local x = torch.rand(ix,iy,iz) local k = torch.rand(kx,ky,kz) local o3 = torch.xcorr3(x,k,'F') local o32 = torch.zeros(o3:size()) for i=1,x:size(1) do for j=1,k:size(1) do o32[i+j-1]:add(torch.xcorr2(x[i],k[k:size(1)-j + 1],'F')) end end mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq') end function torchtest.fconv3_fconv2_eq() local ix = math.floor(torch.uniform(20,40)) local iy = math.floor(torch.uniform(20,40)) local iz = math.floor(torch.uniform(20,40)) local kx = math.floor(torch.uniform(5,10)) local ky = math.floor(torch.uniform(5,10)) local kz = math.floor(torch.uniform(5,10)) local x = torch.rand(ix,iy,iz) local k = torch.rand(kx,ky,kz) local o3 = torch.conv3(x,k,'F') local o32 = torch.zeros(o3:size()) for i=1,x:size(1) do for j=1,k:size(1) do o32[i+j-1]:add(torch.conv2(x[i],k[j],'F')) end end mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq') end function torchtest.logical() local x = torch.rand(100,100)*2-1; local xx = x:clone() local xgt = torch.gt(x,1) local xlt = torch.lt(x,1) local xeq = torch.eq(x,1) local xne = torch.ne(x,1) local neqs = xgt+xlt local all = neqs + xeq mytester:asserteq(neqs:sum(), xne:sum(), 'torch.logical') mytester:asserteq(x:nElement(),all:double():sum() , 'torch.logical') end function torchtest.TestAsserts() mytester:assertError(function() error('hello') end, 'assertError: Error not caught') mytester:assertErrorPattern(function() error('hello') end, '.*ll.*', 'assertError: ".*ll.*" Error not caught') local x = torch.rand(100,100)*2-1; local xx = x:clone(); mytester:assertTensorEq(x, xx, 1e-16, 'assertTensorEq: not deemed equal') mytester:assertTensorNe(x, xx+1, 1e-16, 'assertTensorNe: not deemed different') mytester:assertalmosteq(0, 1e-250, 1e-16, 'assertalmosteq: not deemed different') end function torchtest.BugInAssertTableEq() local t = {1,2,3} local tt = {1,2,3} mytester:assertTableEq(t, tt, 'assertTableEq: not deemed equal') mytester:assertTableNe(t, {3,2,1}, 'assertTableNe: not deemed different') mytester:assertTableEq({1,2,{4,5}}, {1,2,{4,5}}, 'assertTableEq: fails on recursive lists') mytester:assertTableNe(t, {1,2}, 'assertTableNe: different size not deemed different') mytester:assertTableNe(t, {1,2,3,4}, 'assertTableNe: different size not deemed different') end function torchtest.RNGState() local state = torch.getRNGState() local stateCloned = state:clone() local before = torch.rand(1000) mytester:assert(state:ne(stateCloned):long():sum() == 0, 'getRNGState should have value semantics, but appears to have reference semantics') torch.setRNGState(state) local after = torch.rand(1000) mytester:assertTensorEq(before, after, 1e-16, 'getRNGState/setRNGState not generating same sequence') end function torchtest.RNGStateAliasing() torch.manualSeed(1) local unused = torch.uniform() -- Fork the random number stream at this point local gen = torch.Generator() torch.setRNGState(gen, torch.getRNGState()) local target_value = torch.rand(1000) --Dramatically alter the internal state of the main generator local also_unused = torch.rand(100000) local forked_value = torch.rand(gen, 1000) mytester:assertTensorEq(target_value, forked_value, 1e-16, "RNG has not forked correctly.") end function torchtest.testBoxMullerState() torch.manualSeed(123) local odd_number = 101 local seeded = torch.randn(odd_number) local state = torch.getRNGState() local midstream = torch.randn(odd_number) torch.setRNGState(state) local repeat_midstream = torch.randn(odd_number) torch.manualSeed(123) local reseeded = torch.randn(odd_number) mytester:assertTensorEq(midstream, repeat_midstream, 1e-16, 'getRNGState/setRNGState not generating same sequence of normally distributed numbers') mytester:assertTensorEq(seeded, reseeded, 1e-16, 'repeated calls to manualSeed not generating same sequence of normally distributed numbers') end function torchtest.testCholesky() local x = torch.rand(10,10) local A = torch.mm(x, x:t()) local C = torch.potrf(A) local B = torch.mm(C:t(), C) mytester:assertTensorEq(A, B, 1e-14, 'potrf did not allow rebuilding the original matrix') end function torchtest.testNumel() local b = torch.ByteTensor(3, 100, 100) mytester:asserteq(b:nElement(), 3*100*100, "nElement not right") mytester:asserteq(b:numel(), 3*100*100, "numel not right") end -- Generate a tensor of size `size` whose values are ascending integers from -- `start` (or 1, if `start is not given) local function consecutive(size, start) local sequence = torch.ones(torch.Tensor(size):prod(1)[1]):cumsum(1) if start then sequence:add(start - 1) end return sequence:resize(unpack(size)) end function torchtest.index() local badIndexMsg = "Lookup with valid index should return correct result" local reference = consecutive{3, 3, 3} mytester:assertTensorEq(reference[1], consecutive{3, 3}, 1e-16, badIndexMsg) mytester:assertTensorEq(reference[2], consecutive({3, 3}, 10), 1e-16, badIndexMsg) mytester:assertTensorEq(reference[3], consecutive({3, 3}, 19), 1e-16, badIndexMsg) mytester:assertTensorEq(reference[{1}], consecutive{3, 3}, 1e-16, badIndexMsg) mytester:assertTensorEq(reference[{2}], consecutive({3, 3}, 10), 1e-16, badIndexMsg) mytester:assertTensorEq(reference[{3}], consecutive({3, 3}, 19), 1e-16, badIndexMsg) mytester:assertTensorEq(reference[{1,2}], consecutive({3}, 4), 1e-16, badIndexMsg) mytester:assertTensorEq(reference[{{1,2}}], consecutive({2, 3, 3}), 1e-16, badIndexMsg) mytester:asserteq(reference[{3, 3, 3}], 27, badIndexMsg) mytester:assertTensorEq(reference[{}], consecutive{3, 3, 3}, 1e-16, badIndexMsg) local shouldErrorMsg = "Lookup with too many indices should error" mytester:assertError(function() return reference[{1, 1, 1, 1}] end, shouldErrorMsg) mytester:assertError(function() return reference[{1, 1, 1, {1, 1}}] end, shouldErrorMsg) mytester:assertError(function() return reference[{3, 3, 3, 3, 3, 3, 3, 3}] end, shouldErrorMsg) end function torchtest.newIndex() local badIndexMsg = "Assignment to valid index should produce correct result" local reference = consecutive{3, 3, 3} -- This relies on __index__() being correct - but we have separate tests for that local function checkPartialAssign(index) local reference = torch.zeros(3, 3, 3) reference[index] = consecutive{3, 3, 3}[index] mytester:assertTensorEq(reference[index], consecutive{3, 3, 3}[index], 1e-16, badIndexMsg) reference[index] = 0 mytester:assertTensorEq(reference, torch.zeros(3, 3, 3), 1e-16, badIndexMsg) end checkPartialAssign{1} checkPartialAssign{2} checkPartialAssign{3} checkPartialAssign{1,2} checkPartialAssign{2,3} checkPartialAssign{1,3} checkPartialAssign{} local shouldErrorMsg = "Assignment with too many indices should error" mytester:assertError(function() reference[{1, 1, 1, 1}] = 1 end, shouldErrorMsg) mytester:assertError(function() reference[{1, 1, 1, {1, 1}}] = 1 end, shouldErrorMsg) mytester:assertError(function() reference[{3, 3, 3, 3, 3, 3, 3, 3}] = 1 end, shouldErrorMsg) end function torchtest.indexCopy() local nCopy, nDest = 3, 20 local dest = torch.randn(nDest,4,5) local src = torch.randn(nCopy,4,5) local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long() local dest2 = dest:clone() dest:indexCopy(1, idx, src) for i=1,idx:size(1) do dest2[idx[i]]:copy(src[i]) end mytester:assertTensorEq(dest, dest2, 0.000001, "indexCopy tensor error") local dest = torch.randn(nDest) local src = torch.randn(nCopy) local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long() local dest2 = dest:clone() dest:indexCopy(1, idx, src) for i=1,idx:size(1) do dest2[idx[i]] = src[i] end mytester:assertTensorEq(dest, dest2, 0.000001, "indexCopy scalar error") end -- Fill idx with valid indices. local function fillIdx(idx, dim, dim_size, elems_per_row, m, n, o) for i = 1, (dim == 1 and 1 or m) do for j = 1, (dim == 2 and 1 or n) do for k = 1, (dim == 3 and 1 or o) do local ii = {i, j, k} ii[dim] = {} idx[ii] = torch.randperm(dim_size)[{{1, elems_per_row}}] end end end end function torchtest.gather() local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20) local elems_per_row = torch.random(10) local dim = torch.random(3) local src = torch.randn(m, n, o) local idx_size = {m, n, o} idx_size[dim] = elems_per_row local idx = torch.LongTensor():resize(unpack(idx_size)) fillIdx(idx, dim, src:size(dim), elems_per_row, m, n, o) local actual = torch.gather(src, dim, idx) local expected = torch.Tensor():resize(unpack(idx_size)) for i = 1, idx_size[1] do for j = 1, idx_size[2] do for k = 1, idx_size[3] do local ii = {i, j, k} ii[dim] = idx[i][j][k] expected[i][j][k] = src[ii] end end end mytester:assertTensorEq(actual, expected, 0, "Wrong values for gather") idx[1][1][1] = 23 mytester:assertError(function() torch.gather(src, dim, idx) end, "Invalid index not detected") end function torchtest.gatherMax() local src = torch.randn(3, 4, 5) local expected, idx = src:max(3) local actual = torch.gather(src, 3, idx) mytester:assertTensorEq(actual, expected, 0, "Wrong values for gather") end function torchtest.scatter() local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20) local elems_per_row = torch.random(10) local dim = torch.random(3) local idx_size = {m, n, o} idx_size[dim] = elems_per_row local idx = torch.LongTensor():resize(unpack(idx_size)) fillIdx(idx, dim, ({m, n, o})[dim], elems_per_row, m, n, o) local src = torch.Tensor():resize(unpack(idx_size)):normal() local actual = torch.zeros(m, n, o):scatter(dim, idx, src) local expected = torch.zeros(m, n, o) for i = 1, idx_size[1] do for j = 1, idx_size[2] do for k = 1, idx_size[3] do local ii = {i, j, k} ii[dim] = idx[i][j][k] expected[ii] = src[i][j][k] end end end mytester:assertTensorEq(actual, expected, 0, "Wrong values for scatter") idx[1][1][1] = 34 mytester:assertError(function() torch.zeros(m, n, o):scatter(dim, idx, src) end, "Invalid index not detected") end function torchtest.scatterFill() local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20) local elems_per_row = torch.random(10) local dim = torch.random(3) local val = torch.uniform() local idx_size = {m, n, o} idx_size[dim] = elems_per_row local idx = torch.LongTensor():resize(unpack(idx_size)) fillIdx(idx, dim, ({m, n, o})[dim], elems_per_row, m, n, o) local actual = torch.zeros(m, n, o):scatter(dim, idx, val) local expected = torch.zeros(m, n, o) for i = 1, idx_size[1] do for j = 1, idx_size[2] do for k = 1, idx_size[3] do local ii = {i, j, k} ii[dim] = idx[i][j][k] expected[ii] = val end end end mytester:assertTensorEq(actual, expected, 0, "Wrong values for scatter") idx[1][1][1] = 28 mytester:assertError(function() torch.zeros(m, n, o):scatter(dim, idx, val) end, "Invalid index not detected") end function torchtest.maskedCopy() local nCopy, nDest = 3, 10 local dest = torch.randn(nDest) local src = torch.randn(nCopy) local mask = torch.ByteTensor{0,0,0,0,1,0,1,0,1,0} local dest2 = dest:clone() dest:maskedCopy(mask, src) local j = 1 for i=1,nDest do if mask[i] == 1 then dest2[i] = src[j] j = j + 1 end end mytester:assertTensorEq(dest, dest2, 0.000001, "maskedCopy error") -- make source bigger than number of 1s in mask src = torch.randn(nDest) local ok = pcall(dest.maskedCopy, dest, mask, src) mytester:assert(ok, "maskedCopy incorrect complaint when" .. " src is bigger than mask's one count") src = torch.randn(nCopy - 1) -- make src smaller. this should fail local ok = pcall(dest.maskedCopy, dest, mask, src) mytester:assert(not ok, "maskedCopy not erroring when" .. " src is smaller than mask's one count") end function torchtest.maskedSelect() local nSrc = 10 local src = torch.randn(nSrc) local mask = torch.rand(nSrc):mul(2):floor():byte() local dst = torch.Tensor() dst:maskedSelect(src, mask) local dst2 = {} for i=1,nSrc do if mask[i] == 1 then table.insert(dst2, src[i]) end end mytester:assertTensorEq(dst, torch.DoubleTensor(dst2), 0.000001, "maskedSelect error") end function torchtest.maskedFill() local nDst = 10 local dst = torch.randn(nDst) local mask = torch.rand(nDst):mul(2):floor():byte() local val = math.random() local dst2 = dst:clone() dst:maskedFill(mask, val) for i=1,nDst do if mask[i] == 1 then dst2[i] = val end end mytester:assertTensorEq(dst, dst2, 0.000001, "maskedFill error") end function torchtest.abs() local size = 1000 local range = 1000 local original = torch.rand(size):mul(range) -- Tensor filled with {-1,1} local switch = torch.rand(size):mul(2):floor():mul(2):add(-1) local types = {'torch.DoubleTensor', 'torch.FloatTensor', 'torch.LongTensor', 'torch.IntTensor'} for k,t in ipairs(types) do local data = original:type(t) local switch = switch:type(t) local input = torch.cmul(data, switch) mytester:assertTensorEq(input:abs(), data, 1e-16, 'Error in abs() for '..t) end -- Checking that the right abs function is called for LongTensor local bignumber = 2^31 + 1 local input = torch.LongTensor{-bignumber} mytester:assertgt(input:abs()[1], 0, 'torch.abs(3)') end function torchtest.classInModule() -- Need a global for this module _mymodule123 = {} local x = torch.class('_mymodule123.myclass') mytester:assert(x, 'Could not create class in module') -- Remove the global _G['_mymodule123'] = nil end function torchtest.classNoModule() local x = torch.class('_myclass123') mytester:assert(x, 'Could not create class in module') end function torchtest.type() local objects = {torch.DoubleTensor(), {}, nil, 2, "asdf"} local types = {'torch.DoubleTensor', 'table', 'nil', 'number', 'string'} for i,obj in ipairs(objects) do mytester:assert(torch.type(obj) == types[i], "wrong type "..types[i]) end end function torchtest.isTypeOfInheritance() do local A = torch.class('A') local B, parB = torch.class('B', 'A') local C, parC = torch.class('C', 'A') end local a, b, c = A(), B(), C() mytester:assert(torch.isTypeOf(a, 'A'), 'isTypeOf error, string spec') mytester:assert(torch.isTypeOf(a, A), 'isTypeOf error, constructor') mytester:assert(torch.isTypeOf(b, 'B'), 'isTypeOf error child class') mytester:assert(torch.isTypeOf(b, B), 'isTypeOf error child class ctor') mytester:assert(torch.isTypeOf(b, 'A'), 'isTypeOf error: inheritance') mytester:assert(torch.isTypeOf(b, A), 'isTypeOf error: inheritance') mytester:assert(not torch.isTypeOf(c, 'B'), 'isTypeOf error: common parent') mytester:assert(not torch.isTypeOf(c, B), 'isTypeOf error: common parent') end function torchtest.isTensor() local t = torch.randn(3,4) mytester:assert(torch.isTensor(t), 'error in isTensor') mytester:assert(torch.isTensor(t[1]), 'error in isTensor for subTensor') mytester:assert(not torch.isTensor(t[1][2]), 'false positive in isTensor') mytester:assert(torch.Tensor.isTensor(t), 'alias not working') end function torchtest.isStorage() local t = torch.randn(3,4) mytester:assert(torch.isStorage(t:storage()), 'error in isStorage') mytester:assert(not torch.isStorage(t), 'false positive in isStorage') end function torchtest.view() local tensor = torch.rand(15) local template = torch.rand(3,5) local target = template:size():totable() mytester:assertTableEq(tensor:viewAs(template):size():totable(), target, 'Error in viewAs') mytester:assertTableEq(tensor:view(3,5):size():totable(), target, 'Error in view') mytester:assertTableEq(tensor:view(torch.LongStorage{3,5}):size():totable(), target, 'Error in view using LongStorage') mytester:assertTableEq(tensor:view(-1,5):size():totable(), target, 'Error in view using dimension -1') mytester:assertTableEq(tensor:view(3,-1):size():totable(), target, 'Error in view using dimension -1') local tensor_view = tensor:view(5,3) tensor_view:fill(torch.rand(1)[1]) mytester:asserteq((tensor_view-tensor):abs():max(), 0, 'Error in view') local target_tensor = torch.Tensor() mytester:assertTableEq(target_tensor:viewAs(tensor, template):size():totable(), target, 'Error in viewAs') mytester:assertTableEq(target_tensor:view(tensor, 3,5):size():totable(), target, 'Error in view') mytester:assertTableEq(target_tensor:view(tensor, torch.LongStorage{3,5}):size():totable(), target, 'Error in view using LongStorage') mytester:assertTableEq(target_tensor:view(tensor, -1,5):size():totable(), target, 'Error in view using dimension -1') mytester:assertTableEq(target_tensor:view(tensor, 3,-1):size():totable(), target, 'Error in view using dimension -1') target_tensor:fill(torch.rand(1)[1]) mytester:asserteq((target_tensor-tensor):abs():max(), 0, 'Error in viewAs') end function torchtest.expand() local result = torch.Tensor() local tensor = torch.rand(8,1) local template = torch.rand(8,5) local target = template:size():totable() mytester:assertTableEq(tensor:expandAs(template):size():totable(), target, 'Error in expandAs') mytester:assertTableEq(tensor:expand(8,5):size():totable(), target, 'Error in expand') mytester:assertTableEq(tensor:expand(torch.LongStorage{8,5}):size():totable(), target, 'Error in expand using LongStorage') result:expandAs(tensor,template) mytester:assertTableEq(result:size():totable(), target, 'Error in expandAs using result') result:expand(tensor,8,5) mytester:assertTableEq(result:size():totable(), target, 'Error in expand using result') result:expand(tensor,torch.LongStorage{8,5}) mytester:assertTableEq(result:size():totable(), target, 'Error in expand using result and LongStorage') mytester:asserteq((result:mean(2):view(8,1)-tensor):abs():max(), 0, 'Error in expand (not equal)') end function torchtest.repeatTensor() local result = torch.Tensor() local tensor = torch.rand(8,4) local size = {3,1,1} local sizeStorage = torch.LongStorage(size) local target = {3,8,4} mytester:assertTableEq(tensor:repeatTensor(unpack(size)):size():totable(), target, 'Error in repeatTensor') mytester:assertTableEq(tensor:repeatTensor(sizeStorage):size():totable(), target, 'Error in repeatTensor using LongStorage') result:repeatTensor(tensor,unpack(size)) mytester:assertTableEq(result:size():totable(), target, 'Error in repeatTensor using result') result:repeatTensor(tensor,sizeStorage) mytester:assertTableEq(result:size():totable(), target, 'Error in repeatTensor using result and LongStorage') mytester:asserteq((result:mean(1):view(8,4)-tensor):abs():max(), 0, 'Error in repeatTensor (not equal)') end function torchtest.isSameSizeAs() local t1 = torch.Tensor(3, 4, 9, 10) local t2 = torch.Tensor(3, 4) local t3 = torch.Tensor(1, 9, 3, 3) local t4 = torch.Tensor(3, 4, 9, 10) mytester:assert(t1:isSameSizeAs(t2) == false, "wrong answer ") mytester:assert(t1:isSameSizeAs(t3) == false, "wrong answer ") mytester:assert(t1:isSameSizeAs(t4) == true, "wrong answer ") end function torchtest.isSize() local t1 = torch.Tensor(3, 4, 5) local s1 = torch.LongStorage({3, 4, 5}) local s2 = torch.LongStorage({5, 4, 3}) mytester:assert(t1:isSize(s1) == true, "wrong answer ") mytester:assert(t1:isSize(s2) == false, "wrong answer ") mytester:assert(t1:isSize(t1:size()) == true, "wrong answer ") end function torchtest.elementSize() local byte = torch.ByteStorage():elementSize() local char = torch.CharStorage():elementSize() local short = torch.ShortStorage():elementSize() local int = torch.IntStorage():elementSize() local long = torch.LongStorage():elementSize() local float = torch.FloatStorage():elementSize() local double = torch.DoubleStorage():elementSize() mytester:asserteq(byte, torch.ByteTensor():elementSize()) mytester:asserteq(char, torch.CharTensor():elementSize()) mytester:asserteq(short, torch.ShortTensor():elementSize()) mytester:asserteq(int, torch.IntTensor():elementSize()) mytester:asserteq(long, torch.LongTensor():elementSize()) mytester:asserteq(float, torch.FloatTensor():elementSize()) mytester:asserteq(double, torch.DoubleTensor():elementSize()) mytester:assertne(byte, 0) mytester:assertne(char, 0) mytester:assertne(short, 0) mytester:assertne(int, 0) mytester:assertne(long, 0) mytester:assertne(float, 0) mytester:assertne(double, 0) -- These tests are portable, not necessarily strict for your system. mytester:asserteq(byte, 1) mytester:asserteq(char, 1) mytester:assert(short >= 2) mytester:assert(int >= 2) mytester:assert(int >= short) mytester:assert(long >= 4) mytester:assert(long >= int) mytester:assert(double >= float) end function torchtest.split() local result = {} local tensor = torch.rand(7,4) local splitSize = 3 local targetSize = {{3,4},{3,4},{1,4}} local dim = 1 local splits = tensor:split(splitSize, dim) local start = 1 for i, split in ipairs(splits) do mytester:assertTableEq(split:size():totable(), targetSize[i], 'Size error in split '..i) mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.00001, 'Content error in split '..i) start = start + targetSize[i][dim] end torch.split(result, tensor, splitSize, dim) local start = 1 for i, split in ipairs(result) do mytester:assertTableEq(split:size():totable(), targetSize[i], 'Result size error in split '..i) mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.000001, 'Result content error in split '..i) start = start + targetSize[i][dim] end mytester:asserteq(#splits,#result, 0, 'Non-consistent output size from split') for i, split in ipairs(splits) do mytester:assertTensorEq(split,result[i], 0, 'Non-consistent outputs from split') end end function torchtest.chunk() local result = {} local tensor = torch.rand(4,7) local nChunk = 3 local targetSize = {{4,3},{4,3},{4,1}} local dim = 2 local splits = tensor:chunk(nChunk, dim) local start = 1 for i, split in ipairs(splits) do mytester:assertTableEq(split:size():totable(), targetSize[i], 'Size error in chunk '..i) mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.00001, 'Content error in chunk '..i) start = start + targetSize[i][dim] end torch.split(result, tensor, nChunk, dim) local start = 1 for i, split in ipairs(result) do mytester:assertTableEq(split:size():totable(), targetSize[i], 'Result size error in chunk '..i) mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.000001, 'Result content error in chunk '..i) start = start + targetSize[i][dim] end end function torchtest.totable() local table1D = {1, 2, 3} local tensor1D = torch.Tensor(table1D) local storage = torch.Storage(table1D) mytester:assertTableEq(tensor1D:totable(), table1D, 'tensor1D:totable incorrect') mytester:assertTableEq(storage:totable(), table1D, 'storage:totable incorrect') mytester:assertTableEq(torch.totable(tensor1D), table1D, 'torch.totable incorrect for Tensors') mytester:assertTableEq(torch.totable(storage), table1D, 'torch.totable incorrect for Storages') local table2D = {{1, 2}, {3, 4}} local tensor2D = torch.Tensor(table2D) mytester:assertTableEq(tensor2D:totable(), table2D, 'tensor2D:totable incorrect') local tensor3D = torch.Tensor({{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}) local tensorNonContig = tensor3D:select(2, 2) mytester:assert(not tensorNonContig:isContiguous(), 'invalid test') mytester:assertTableEq(tensorNonContig:totable(), {{3, 4}, {7, 8}}, 'totable() incorrect for non-contiguous tensors') end function torchtest.permute() local orig = {1,2,3,4,5,6,7} local perm = torch.randperm(7):totable() local x = torch.Tensor(unpack(orig)):fill(0) local new = x:permute(unpack(perm)):size():totable() mytester:assertTableEq(perm, new, 'Tensor:permute incorrect') mytester:assertTableEq(x:size():totable(), orig, 'Tensor:permute changes tensor') end function torchtest.serialize() local tableObj = {6, a = 42} local tensObj = torch.randn(3,4,5) -- Test serializing a table local serString = torch.serialize(tableObj) local serStorage = torch.serializeToStorage(tableObj) mytester:assertTableEq(tableObj, torch.deserialize(serString)) mytester:assertTableEq(tableObj, torch.deserializeFromStorage(serStorage)) -- Test serializing a Tensor serString = torch.serialize(tensObj) serStorage = torch.serializeToStorage(tensObj) mytester:assertTensorEq(tensObj, torch.deserialize(serString), 1e-10) mytester:assertTensorEq(tensObj, torch.deserializeFromStorage(serStorage), 1e-10) end function torchtest.storageview() local s1 = torch.LongStorage({3, 4, 5}) local s2 = torch.LongStorage(s1, 2) mytester:assert(s2:size() == 2, "should be size 2") mytester:assert(s2[1] == s1[2], "should have 4 at position 1") mytester:assert(s2[2] == s1[3], "should have 5 at position 2") s2[1] = 13 mytester:assert(13 == s1[2], "should have 13 at position 1") end function torch.test(tests) math.randomseed(os.time()) if torch.getdefaulttensortype() == 'torch.FloatTensor' then precision = 1e-4 elseif torch.getdefaulttensortype() == 'torch.DoubleTensor' then precision = 1e-8 end mytester = torch.Tester() mytester:add(torchtest) mytester:run(tests) return mytester end
bsd-3-clause
crabman77/minetest-minetestforfun-server
mods/mesecons/mesecons_mvps/init.lua
9
7255
--register stoppers for movestones/pistons mesecon.mvps_stoppers = {} mesecon.on_mvps_move = {} mesecon.mvps_unmov = {} --- Objects (entities) that cannot be moved function mesecon.register_mvps_unmov(objectname) mesecon.mvps_unmov[objectname] = true; end function mesecon.is_mvps_unmov(objectname) return mesecon.mvps_unmov[objectname] end -- Nodes that cannot be pushed / pulled by movestones, pistons function mesecon.is_mvps_stopper(node, pushdir, stack, stackid) -- unknown nodes are always stoppers if not minetest.registered_nodes[node.name] then return true end local get_stopper = mesecon.mvps_stoppers[node.name] if type (get_stopper) == "function" then get_stopper = get_stopper(node, pushdir, stack, stackid) end return get_stopper end function mesecon.register_mvps_stopper(nodename, get_stopper) if get_stopper == nil then get_stopper = true end mesecon.mvps_stoppers[nodename] = get_stopper end -- Functions to be called on mvps movement function mesecon.register_on_mvps_move(callback) mesecon.on_mvps_move[#mesecon.on_mvps_move+1] = callback end local function on_mvps_move(moved_nodes) for _, callback in ipairs(mesecon.on_mvps_move) do callback(moved_nodes) end end function mesecon.mvps_process_stack(stack) -- update mesecons for placed nodes ( has to be done after all nodes have been added ) for _, n in ipairs(stack) do mesecon.on_placenode(n.pos, minetest.get_node(n.pos)) end end -- tests if the node can be pushed into, e.g. air, water, grass local function node_replaceable(name) if name == "ignore" then return true end if minetest.registered_nodes[name] then return minetest.registered_nodes[name].buildable_to or false end return false end function mesecon.mvps_get_stack(pos, dir, maximum, all_pull_sticky) -- determine the number of nodes to be pushed local nodes = {} local frontiers = {pos} while #frontiers > 0 do local np = frontiers[1] local nn = minetest.get_node(np) if not node_replaceable(nn.name) then table.insert(nodes, {node = nn, pos = np}) if #nodes > maximum then return nil end -- add connected nodes to frontiers, connected is a vector list -- the vectors must be absolute positions local connected = {} if minetest.registered_nodes[nn.name] and minetest.registered_nodes[nn.name].mvps_sticky then connected = minetest.registered_nodes[nn.name].mvps_sticky(np, nn) end table.insert(connected, vector.add(np, dir)) -- If adjacent node is sticky block and connects add that -- position to the connected table for _, r in ipairs(mesecon.rules.alldirs) do local adjpos = vector.add(np, r) local adjnode = minetest.get_node(adjpos) if minetest.registered_nodes[adjnode.name] and minetest.registered_nodes[adjnode.name].mvps_sticky then local sticksto = minetest.registered_nodes[adjnode.name] .mvps_sticky(adjpos, adjnode) -- connects to this position? for _, link in ipairs(sticksto) do if vector.equals(link, np) then table.insert(connected, adjpos) end end end end if all_pull_sticky then table.insert(connected, vector.subtract(np, dir)) end -- Make sure there are no duplicates in frontiers / nodes before -- adding nodes in "connected" to frontiers for _, cp in ipairs(connected) do local duplicate = false for _, rp in ipairs(nodes) do if vector.equals(cp, rp.pos) then duplicate = true end end for _, fp in ipairs(frontiers) do if vector.equals(cp, fp) then duplicate = true end end if not duplicate then table.insert(frontiers, cp) end end end table.remove(frontiers, 1) end return nodes end function mesecon.mvps_push(pos, dir, maximum) return mesecon.mvps_push_or_pull(pos, dir, dir, maximum) end function mesecon.mvps_pull_all(pos, dir, maximum) return mesecon.mvps_push_or_pull(pos, vector.multiply(dir, -1), dir, maximum, true) end function mesecon.mvps_pull_single(pos, dir, maximum) return mesecon.mvps_push_or_pull(pos, vector.multiply(dir, -1), dir, maximum) end -- pos: pos of mvps; stackdir: direction of building the stack -- movedir: direction of actual movement -- maximum: maximum nodes to be pushed -- all_pull_sticky: All nodes are sticky in the direction that they are pulled from function mesecon.mvps_push_or_pull(pos, stackdir, movedir, maximum, all_pull_sticky) local nodes = mesecon.mvps_get_stack(pos, movedir, maximum, all_pull_sticky) if not nodes then return end -- determine if one of the nodes blocks the push / pull for id, n in ipairs(nodes) do if mesecon.is_mvps_stopper(n.node, movedir, nodes, id) then return end end -- remove all nodes for _, n in ipairs(nodes) do n.meta = minetest.get_meta(n.pos):to_table() minetest.remove_node(n.pos) end -- update mesecons for removed nodes ( has to be done after all nodes have been removed ) for _, n in ipairs(nodes) do mesecon.on_dignode(n.pos, n.node) end -- add nodes for _, n in ipairs(nodes) do local np = vector.add(n.pos, movedir) minetest.set_node(np, n.node) minetest.get_meta(np):from_table(n.meta) end local moved_nodes = {} local oldstack = mesecon.tablecopy(nodes) for i in ipairs(nodes) do moved_nodes[i] = {} moved_nodes[i].oldpos = nodes[i].pos nodes[i].pos = vector.add(nodes[i].pos, movedir) moved_nodes[i].pos = nodes[i].pos moved_nodes[i].node = nodes[i].node moved_nodes[i].meta = nodes[i].meta end on_mvps_move(moved_nodes) return true, nodes, oldstack end mesecon.register_on_mvps_move(function(moved_nodes) for _, n in ipairs(moved_nodes) do mesecon.on_placenode(n.pos, n.node) mesecon.update_autoconnect(n.pos) end end) function mesecon.mvps_move_objects(pos, dir, nodestack) local objects_to_move = {} -- Move object at tip of stack, pushpos is position at tip of stack local pushpos = vector.add(pos, vector.multiply(dir, #nodestack)) local objects = minetest.get_objects_inside_radius(pushpos, 1) for _, obj in ipairs(objects) do table.insert(objects_to_move, obj) end -- Move objects lying/standing on the stack (before it was pushed - oldstack) if tonumber(minetest.setting_get("movement_gravity")) > 0 and dir.y == 0 then -- If gravity positive and dir horizontal, push players standing on the stack for _, n in ipairs(nodestack) do local p_above = vector.add(n.pos, {x=0, y=1, z=0}) local objects = minetest.get_objects_inside_radius(p_above, 1) for _, obj in ipairs(objects) do table.insert(objects_to_move, obj) end end end for _, obj in ipairs(objects_to_move) do local entity = obj:get_luaentity() if not entity or not mesecon.is_mvps_unmov(entity.name) then local np = vector.add(obj:getpos(), dir) --move only if destination is not solid local nn = minetest.get_node(np) if not ((not minetest.registered_nodes[nn.name]) or minetest.registered_nodes[nn.name].walkable) then obj:setpos(np) end end end end mesecon.register_mvps_stopper("doors:door_steel_b_1") mesecon.register_mvps_stopper("doors:door_steel_t_1") mesecon.register_mvps_stopper("doors:door_steel_b_2") mesecon.register_mvps_stopper("doors:door_steel_t_2") mesecon.register_mvps_stopper("default:chest_locked")
unlicense
kitala1/darkstar
scripts/zones/Norg/npcs/Keal.lua
17
4228
----------------------------------- -- Area: Norg -- NPC: Keal -- Starts and Ends Quest: It's Not Your Vault ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); local path = { -5.453587, 0.151494, -16.361458, -5.997250, 0.229052, -15.475480, -6.582538, 0.317294, -14.524694, -7.573528, 0.365118, -12.941586, -7.069273, 0.384884, -13.867216, -6.565747, 0.311785, -14.741985, -5.676943, 0.173223, -16.241194, -5.162223, 0.020922, -17.108603, -4.725273, -0.022554, -18.175083, -4.882753, -0.041670, -19.252790, -5.294413, 0.020847, -20.336269, -5.632565, 0.112649, -21.417961, -5.905818, 0.202903, -22.541668, -5.657803, 0.116744, -21.445057, -5.273734, 0.023316, -20.410303, -4.831870, -0.049031, -19.478870, -4.749702, -0.024804, -18.311924, -5.152854, 0.002354, -17.248878, -5.639069, 0.185855, -16.335281, -6.158780, 0.247668, -15.445805, -7.253261, 0.405026, -13.567613, -7.803670, 0.348802, -12.626184, -8.375298, 0.223101, -11.645775, -8.895057, 0.076541, -10.770375, -9.384287, 0.015579, -9.884774, -9.939011, 0.143451, -8.935238, -9.422630, -0.025280, -9.816562, -8.589481, 0.151451, -11.248314, -8.095008, 0.275576, -12.123538, -7.561854, 0.373715, -13.045633, -5.644930, 0.185392, -16.292952, -5.058481, -0.014674, -17.285294, -4.724863, -0.024709, -18.265087, -4.923457, -0.042915, -19.378429, -5.293544, 0.020505, -20.338196, -5.606711, 0.104830, -21.323364, -5.849701, 0.183865, -22.302536, -5.586438, 0.097169, -21.222555, -5.214560, 0.046522, -20.280220, -4.779529, -0.048305, -19.351633, -4.757209, -0.021693, -18.194023, -5.138152, -0.000450, -17.254173, -5.685457, 0.173866, -16.248564, -6.275849, 0.266052, -15.243981, -7.196375, 0.403362, -13.666089, -7.766060, 0.352119, -12.689950, -8.280642, 0.241637, -11.799251, -8.828505, 0.098458, -10.895535, -9.351592, 0.039748, -9.948843, -9.856394, 0.036026, -9.068656 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Vault = player:getQuestStatus(OUTLANDS,ITS_NOT_YOUR_VAULT); mLvl = player:getMainLvl(); IronBox = player:hasKeyItem(SEALED_IRON_BOX); if(Vault == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3 and mLvl >= 5) then player:startEvent(0x0024,SEALED_IRON_BOX); -- Start quest elseif(Vault == QUEST_ACCEPTED) then if(IronBox == true) then player:startEvent(0x0026); -- Finish quest else player:startEvent(0x0025,MAP_OF_THE_SEA_SERPENT_GROTTO); -- Reminder/Directions Dialogue end elseif(Vault == QUEST_COMPLETED) then player:startEvent(0x0027); -- New Standard Dialogue for everyone who has completed the quest else player:startEvent(0x0059); -- Standard Conversation end npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0024 and option == 1) then player:addQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); elseif (csid == 0x0026) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4961); else player:delKeyItem(SEALED_IRON_BOX); player:addItem(4961); -- Scroll of Tonko: Ichi player:messageSpecial(ITEM_OBTAINED, 4961); player:addFame(OUTLANDS,NORG_FAME*50); player:completeQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); end end npc:wait(0); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Northern_San_dOria/npcs/Morunaude.lua
36
1428
----------------------------------- -- Area: Northern San d'Oria -- NPC: Morunaude -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x027a); 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
theonlywild/erfaaan
plugins/feedback.lua
1
1028
do function run(msg, matches) local fuse = '#DearAdmin , we have recive a new feedback just now : #newfeedback \n\nID : ' .. msg.from.id .. '\n\nName : ' .. msg.from.print_name ..'\n\nusername : @' .. msg.from.username ..'\n\nFeedBack :\n\n\n' .. matches[1] local fuses = '!printf user#id' .. msg.from.id local text = matches[1] bannedidone = string.find(msg.from.id, '123') bannedidtwo =string.find(msg.from.id, '465') bannedidthree =string.find(msg.from.id, '678') print(msg.to.id) if bannedidone or bannedidtwo or bannedidthree then --for banned people return 'You are banned to send a feedback' else local sends0 = send_msg('chat#94293138', fuse, ok_cb, false) return 'ارسال شد :)' end end return { description = "Feedback", usage = "ارسال نظر : send maseage to admins with bot", patterns = { "^ارسال نظر (.*)$" }, run = run } end --add your realm id to line 22 chat#
gpl-2.0
shdown/luastatus
examples/i3/weather.lua
1
2091
-- you need to install 'luasec' module (e.g. with luarocks) -- you can look up all available flags here: https://github.com/chubin/wttr.in#one-line-output local https = require('ssl.https') local ltn12 = require('ltn12') -- All the arguments except for 'url' may be absent or nil; default method is GET. -- Returns: code (integer), body (string), headers (table), status (string). function request(url, headers, method, body) local out_body = {} local is_ok, code_or_errmsg, out_headers, status = https.request( { url = url, sink = ltn12.sink.table(out_body), redirect = false, cafile = '/etc/ssl/certs/ca-certificates.crt', verify = 'peer', method = method, headers = headers, }, body) assert(is_ok, code_or_errmsg) return code_or_errmsg, table.concat(out_body), out_headers, status end -- Arguments are the same to those of 'request'. -- Returns: body (string), headers (table). function request_check_code(...) local code, body, headers, status = request(...) assert(code == 200, string.format('HTTP %s %s', code, status)) return body, headers end function urlencode(s) return string.gsub(s, '[^-_.~a-zA-Z0-9]', function(c) return string.format('%%%02X', string.byte(c)) end) end local BASE_URL = 'wttr.in' local LANG = 'en' local LOCATION = '' function get_weather(format) -- encoding is needed to allow usage of special use characters format = urlencode(format) local url = string.format('https://%s.%s/%s?format=%s', LANG, BASE_URL, LOCATION, format) local is_ok, body = pcall(request_check_code, url) if is_ok then return body:gsub("\n", "") else return nil end end widget = { plugin = 'timer', opts = {period = 15 * 60}, cb = function() local text = get_weather('%l: %C %t(%f)') if text == nil then luastatus.plugin.push_period(60) -- retry in 60 seconds text = '......' end return {full_text = text} end, }
gpl-3.0
kitala1/darkstar
scripts/zones/Caedarva_Mire/npcs/qm3.lua
8
1187
----------------------------------- -- Area: Caedarva Mire -- NPC: ??? (Spawn Mahjlaef the Paintorn(ZNM T3)) -- @pos 695 -7 527 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2594,1) and trade:getItemCount() == 1) then -- Trade Exorcism Treatise player:tradeComplete(); SpawnMob(17101204,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
DangerCove/libquvi-scripts
share/lua/website/justintv.lua
4
2392
-- libquvi-scripts -- Copyright (C) 2012 quvi project <http://quvi.sourceforge.net/> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} local domains = {"twitch%.tv", "justin%.tv"} r.domain = table.concat(domains, "|") r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, domains, {"/[%w_]+/b/%d+"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "justintv" self.id = self.page_url:match("/[%w_]+/b/(%d+)") or error("no match: media ID") local c_url = "http://api.justin.tv/api/clip/show/" .. self.id .. ".xml" local c = quvi.fetch(c_url, {fetch_type = 'config'}) self.title = c:match('<title>(.-)</title>') or '' if #self.title ==0 then c = c:gsub("^%s*(.-)%s*$", "%1") -- 'c' may hold an error message. c = c:gsub("%s%s+", " ") -- Sanitize. error(string.format("no match: media title (%s)", (#c >0) and c or '')) end self.thumbnail_url = c:match('<image_url_medium>(.-)</image_url_medium>') or '' self.url = {c:match("<video_file_url>(.-)</video_file_url>") or error("no match: media URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
lgpl-2.1
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua
3
15538
-------------------------------- -- @module ParticleSystem -- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#ParticleSystem] getStartSizeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getTexture -- @param self -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- @function [parent=#ParticleSystem] isFull -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] getBatchNode -- @param self -- @return ParticleBatchNode#ParticleBatchNode ret (return value: cc.ParticleBatchNode) -------------------------------- -- @function [parent=#ParticleSystem] getStartColor -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- @function [parent=#ParticleSystem] getPositionType -- @param self -- @return ParticleSystem::PositionType#ParticleSystem::PositionType ret (return value: cc.ParticleSystem::PositionType) -------------------------------- -- @function [parent=#ParticleSystem] setPosVar -- @param self -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#ParticleSystem] getEndSpin -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setRotatePerSecondVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getStartSpinVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getRadialAccelVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getEndSizeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setRotation -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setTangentialAccel -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setScaleY -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setScaleX -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getRadialAccel -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setStartRadius -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setRotatePerSecond -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setEndSize -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getGravity -- @param self -- @return Vec2#Vec2 ret (return value: cc.Vec2) -------------------------------- -- @function [parent=#ParticleSystem] getTangentialAccel -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setEndRadius -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getSpeed -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getAngle -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setEndColor -- @param self -- @param #color4f_table color4f -------------------------------- -- @function [parent=#ParticleSystem] setStartSpin -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setDuration -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setTexture -- @param self -- @param #cc.Texture2D texture2d -------------------------------- -- @function [parent=#ParticleSystem] getPosVar -- @param self -- @return Vec2#Vec2 ret (return value: cc.Vec2) -------------------------------- -- @function [parent=#ParticleSystem] updateWithNoTime -- @param self -------------------------------- -- @function [parent=#ParticleSystem] isBlendAdditive -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] getSpeedVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setPositionType -- @param self -- @param #cc.ParticleSystem::PositionType positiontype -------------------------------- -- @function [parent=#ParticleSystem] stopSystem -- @param self -------------------------------- -- @function [parent=#ParticleSystem] getSourcePosition -- @param self -- @return Vec2#Vec2 ret (return value: cc.Vec2) -------------------------------- -- @function [parent=#ParticleSystem] setLifeVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setTotalParticles -- @param self -- @param #int int -------------------------------- -- @function [parent=#ParticleSystem] setEndColorVar -- @param self -- @param #color4f_table color4f -------------------------------- -- @function [parent=#ParticleSystem] updateQuadWithParticle -- @param self -- @param #cc.sParticle sparticle -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#ParticleSystem] getAtlasIndex -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#ParticleSystem] getStartSize -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setStartSpinVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] resetSystem -- @param self -------------------------------- -- @function [parent=#ParticleSystem] setAtlasIndex -- @param self -- @param #int int -------------------------------- -- @function [parent=#ParticleSystem] setTangentialAccelVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setEndRadiusVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getEndRadius -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] isActive -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] setRadialAccelVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setStartSize -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setSpeed -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getStartSpin -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getRotatePerSecond -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] initParticle -- @param self -- @param #cc.sParticle sparticle -------------------------------- -- @function [parent=#ParticleSystem] setEmitterMode -- @param self -- @param #cc.ParticleSystem::Mode mode -------------------------------- -- @function [parent=#ParticleSystem] getDuration -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setSourcePosition -- @param self -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#ParticleSystem] getEndSpinVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setBlendAdditive -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ParticleSystem] setLife -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setAngleVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setRotationIsDir -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ParticleSystem] setEndSizeVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setAngle -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setBatchNode -- @param self -- @param #cc.ParticleBatchNode particlebatchnode -------------------------------- -- @function [parent=#ParticleSystem] getTangentialAccelVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getEmitterMode -- @param self -- @return ParticleSystem::Mode#ParticleSystem::Mode ret (return value: cc.ParticleSystem::Mode) -------------------------------- -- @function [parent=#ParticleSystem] setEndSpinVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getAngleVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setStartColor -- @param self -- @param #color4f_table color4f -------------------------------- -- @function [parent=#ParticleSystem] getRotatePerSecondVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getEndSize -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getLife -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setSpeedVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setAutoRemoveOnFinish -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ParticleSystem] setGravity -- @param self -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#ParticleSystem] postStep -- @param self -------------------------------- -- @function [parent=#ParticleSystem] setEmissionRate -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getEndColorVar -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- @function [parent=#ParticleSystem] getRotationIsDir -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] setScale -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getEmissionRate -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getEndColor -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- @function [parent=#ParticleSystem] getLifeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setStartSizeVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setOpacityModifyRGB -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ParticleSystem] addParticle -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] getStartRadius -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getParticleCount -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- @function [parent=#ParticleSystem] getStartRadiusVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] setStartColorVar -- @param self -- @param #color4f_table color4f -------------------------------- -- @function [parent=#ParticleSystem] setEndSpin -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] setRadialAccel -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] isAutoRemoveOnFinish -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] getTotalParticles -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#ParticleSystem] setStartRadiusVar -- @param self -- @param #float float -------------------------------- -- @function [parent=#ParticleSystem] getEndRadiusVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ParticleSystem] getStartColorVar -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- @function [parent=#ParticleSystem] create -- @param self -- @param #string str -- @return ParticleSystem#ParticleSystem ret (return value: cc.ParticleSystem) -------------------------------- -- @function [parent=#ParticleSystem] createWithTotalParticles -- @param self -- @param #int int -- @return ParticleSystem#ParticleSystem ret (return value: cc.ParticleSystem) -------------------------------- -- @function [parent=#ParticleSystem] update -- @param self -- @param #float float return nil
mit
kitala1/darkstar
scripts/zones/Windurst_Waters/npcs/Cochal-Monchal.lua
19
1585
----------------------------------- -- Area: Windurst Waters -- NPC: Cochal-Monchal -- Involved in Quest: Dark Legacy -- @zone 238 -- @pos -52 -6 110 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getVar("darkLegacyCS") == 2) then player:startEvent(0x02b9,0,DARKSTEEL_FORMULA); elseif(player:getVar("darkLegacyCS") == 3) then player:startEvent(0x02ba,0,DARKSTEEL_FORMULA); elseif(player:hasKeyItem(DARKSTEEL_FORMULA)) then player:startEvent(0x02bb,0,DARKSTEEL_FORMULA); else player:startEvent(0x2b8); 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 == 0x02b9) then player:setVar("darkLegacyCS",3); player:delKeyItem(LETTER_FROM_THE_DARKSTEEL_FORGE); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/istiridye.lua
18
1346
----------------------------------------- -- ID: 5456 -- Item: Istiridye -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense +17.07% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5456); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEFP, 17.07); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEFP, 17.07); end;
gpl-3.0
crabman77/minetest-minetestforfun-server
mods/_misc/nointeract_messages.lua
10
1065
local players = {} local function tick(name) if players[name] == nil then return end if not minetest.get_player_by_name(name) or minetest.check_player_privs(name, {interact=true}) == true then players[name] = nil return end if minetest.check_player_privs(name, {shout=true}) then minetest.chat_send_player(name, "Hey " .. name .. " ! Pour pouvoir construire et intéragir sur ce serveur, tu dois lire les règles du serveur et les accepter. Tape /rules.") minetest.chat_send_player(name, "Hey " .. name .. " ! To build and interact on this server, you have to read the rules of our server and agree them. Type /rules.") end minetest.after(20, tick, name) end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if not minetest.check_player_privs(name, {interact=true}) and players[name] == nil then minetest.after(7, tick, name) players[name] = true end end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() if not name then return end players[name] = nil end)
unlicense
kitala1/darkstar
scripts/globals/items/buttered_nebimonite.lua
35
1401
----------------------------------------- -- ID: 4267 -- Item: Buttered Nebimonite -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 1 -- Vitality 2 -- defense % 25 -- defense Cap 75 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4267); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 75); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 75); end;
gpl-3.0
Eternym/psychoactive2
data/talkactions/scripts/alladdons.lua
1
1229
local looktypes = { 128, 136, 129, 137, 130, 138, 131, 139, 132, 140, 133, 141, 134, 142, 143, 147, 144, 148, 145, 149, 146, 150, 151, 155, 152, 156, 153, 157, 154, 158, 251, 252, 268, 269, 273, 270, 278, 279, 289, 288, 325, 324, 335, 336, 366, 367, 328, 329 } function onSay(player, words, param) if not player:getGroup():getAccess() then return true end local target if param == '' then target = player:getTarget() if not target then player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, 'Gives players the ability to wear all addons. Usage: /addons <player name>') return false end else target = Player(param) end if not target then player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, 'Player ' .. param .. ' is currently not online.') return false end if player:getAccountType() < ACCOUNT_TYPE_GOD then player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, 'Cannot perform action.') return false end for i = 1, #looktypes do target:addOutfitAddon(looktypes[i], 3) end player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, 'All addons unlocked for ' .. target:getName() .. '.') target:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, '[Server] All addons unlocked.') return false end
gpl-2.0
kitala1/darkstar
scripts/zones/Dynamis-Windurst/Zone.lua
28
2485
----------------------------------- -- -- Zone: Dynamis-Windurst -- ----------------------------------- package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Dynamis-Windurst/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaWindurst]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1282); if (inst == 1) then player:bcnmEnter(1282); else cs = 0; end else player:bcnmEnter(1282); end else inst = player:bcnmRegister(1282); if (inst == 1) then player:bcnmEnter(1282); else cs = 0; end end else cs = 0; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0) then player:setPos(-217.000,1.000,-119.000,94,0xEF); end end;
gpl-3.0
Sulunia/beatfever
modules/externals/lovedebug.lua
1
26575
--local _Debug table for holding all variables local _Debug = { errors = {}, prints = {}, order = {}, --e for errors, p for prints onTopFeed = {}, orderOffset = 0, longestOffset = 0, drawOverlay = false, tickTime = 0.5, tick = 0.5, drawTick = true, input = "", inputMarker = 0, lastH = nil, lastCut = nil, lastRows = 1, history = {''}, historyIndex = 1, Font = love.graphics.newFont(12), BigFont = love.graphics.newFont(24), Proposals = {}, ProposalLocation = _G; Proposal_String = "", trackKeys = {}, keyRepeatInterval = 0.05, keyRepeatDelay = 0.4, liveOutput='', liveLastModified=love.filesystem.getLastModified('main.lua'), liveDo=false } --Settings _DebugSettings = { MultipleErrors = false, OverlayColor = {0, 0, 0}, DrawOnTop = true, LiveAuto = false, LiveFile = 'main.lua', LiveReset = false, HaltExecution = false, AutoScroll = false, } --Print all settings _DebugSettings.Settings = function() print("Settings:") print(" _DebugSettings.MultipleErrors [Boolean] Controls if errors should appear multiple times, default is false") print(" _DebugSettings.OverlayColor [{int, int, int}] Sets the color of the overlay, default is {0,0,0}") print(" _DebugSettings.LiveAuto [Boolean] Check if the code should be reloaded when it's modified, default is false") print(" _DebugSettings.LiveFile [String] Sets the file that lovedebug reloads, default is 'main.lua'") print(" _DebugSettings.LiveFile [{String,String,...}] Sets the files, has a table, that lovedebug reloads, can be multiple") print(" _DebugSettings.LiveReset [Boolean] Rather or not love.load() should be reloaded if the code is HotSwapped, default is false") print(" _DebugSettings.DrawOnTop [Boolean] If the errors and prints should be dispalyed on top of the screen, default is false") print(" _DebugSettings.HaltExecution [Boolean] Rather or not to halt program execution while console is open, default is true") print(" _DebugSettings.AutoScroll [Boolean] Rather or not to auto scroll the console once output fills up the console, default is false") end local super_print = print --Override print and call super _G["print"] = function(...) super_print(...) local str = {} for i = 1, select('#', ...) do str[i] = tostring(select(i, ...)) end table.insert(_Debug.prints, table.concat(str, " ")) table.insert(_Debug.order, "p" .. tostring(#_Debug.prints)) table.insert(_Debug.onTopFeed, {"p" .. tostring(#_Debug.prints),0}) end --Error catcher _Debug.handleError = function(err) if _DebugSettings.MultipleErrors == false then for i,v in pairs(_Debug.errors) do if v == err then return --Don't print the same error multiple times! end end end table.insert(_Debug.errors, err) table.insert(_Debug.order, "e" .. tostring(#_Debug.errors)) table.insert(_Debug.onTopFeed, {"e" .. tostring(#_Debug.errors),0}) end --Get Linetype _Debug.lineInfo = function(str) local prefix = string.sub(str, 1, 1) local err = (prefix == "e") local index = tonumber(str:sub(2)) return err, index end --On Top drawer _Debug.onTop = function() love.graphics.push() love.graphics.origin() love.graphics.setFont(_Debug.Font) local font = love.graphics.getFont() local r, g, b, a = love.graphics.getColor() local p,e = {},{} for i,v in ipairs(_Debug.onTopFeed) do err, index = _Debug.lineInfo(v[1]) --Obtain message and type msg = err and _Debug.errors[index] or _Debug.prints[index] if err then table.insert(e,{msg,i}) else table.insert(p,{msg,i}) end end if #p > 0 then love.graphics.setColor(127, 127, 127, 255) love.graphics.rectangle('fill', 0, 0, love.graphics.getWidth()/2, 2) end if #e > 0 then love.graphics.setColor(255, 0, 0, 255) love.graphics.rectangle('fill', love.graphics.getWidth()/2, 0, love.graphics.getWidth()/2, 2) end if p then --draw prints love.graphics.setScissor(0,0,love.graphics.getWidth()/2,2+ 5*((#p-1) > -1 and #p-1 or 0) + #p*_Debug.Font:getHeight()) love.graphics.setColor(127, 127, 127, 64) love.graphics.rectangle('fill',0,1,love.graphics.getWidth()/2,2+ 5*((#p-1) > -1 and #p-1 or 0) + #p*_Debug.Font:getHeight()) love.graphics.setColor(255, 255, 255, 255) for i,v in ipairs(p) do love.graphics.print(v[1], 5, 2+ 5*(i-1) + (i-1)*_Debug.Font:getHeight()) end end if e then --draw errors love.graphics.setScissor(love.graphics.getWidth()/2,0,love.graphics.getWidth()/2,2+ 5*((#e-1) > -1 and #e-1 or 0) + #e*_Debug.Font:getHeight()) love.graphics.setColor(255, 0, 0, 64) love.graphics.rectangle('fill',love.graphics.getWidth()/2,1,love.graphics.getWidth()/2,2+ 5*((#e-1) > -1 and #e-1 or 0) + #e*_Debug.Font:getHeight()) love.graphics.setColor(255, 255, 255, 255) for i,v in ipairs(e) do love.graphics.print(v[1], love.graphics.getWidth()/2+5, 2+ 5*(i-1) + (i-1)*_Debug.Font:getHeight()) end end love.graphics.setScissor() love.graphics.setColor(r, g, b, a) if font then love.graphics.setFont(font) end love.graphics.pop() end _Debug.onTopUpdate = function(dt) local rmv = {} for i,v in ipairs(_Debug.onTopFeed) do if v[2] >= 6 then table.insert(rmv,i) else _Debug.onTopFeed[1][2] = _Debug.onTopFeed[1][2] +dt end end for i,v in ipairs(rmv) do table.remove(_Debug.onTopFeed,v) end end --Overlay drawer _Debug.overlay = function() love.graphics.push() love.graphics.origin() love.graphics.setStencilTest() local font = love.graphics.getFont() local r, g, b, a = love.graphics.getColor() local fontSize = _Debug.Font:getHeight() local w = love.graphics.getWidth() local h = love.graphics.getHeight() local R, G, B = unpack(_DebugSettings.OverlayColor) love.graphics.setColor(R, G, B, 220) love.graphics.rectangle("fill", 0, 0, w, h) love.graphics.setColor(255, 255, 255) love.graphics.setFont(_Debug.Font) local count = 0 local cutY = 0 if h ~= _Debug.lastH then --Did the height of the window change? local _cutY = h - 40 cutY = _cutY local rows = 0 while rows * (fontSize + 2) < _cutY do --Find out how long the scissor should be rows = rows + 1 cutY = rows * (fontSize + 2) end _Debug.lastRows = rows else cutY = _Debug.lastCut --Use the last good value end love.graphics.setScissor(0, 0, w, cutY + 1) local drawing_length = #_Debug.order if 1 + _Debug.orderOffset + _Debug.lastRows < drawing_length then drawing_length = 1 + _Debug.orderOffset + _Debug.lastRows end for i = 1 + _Debug.orderOffset, drawing_length do count = count + 1 local v = _Debug.order[i] local x = 5 local y = (fontSize + 2) * count local err, index = _Debug.lineInfo(v) --Obtain message and type local msg = err and _Debug.errors[index] or _Debug.prints[index] if err then --Add a red and fancy prefix love.graphics.setColor(255, 0, 0) love.graphics.print("[Error]", x, y) x = 50 end love.graphics.setColor(255, 255, 255) love.graphics.print(msg, x, y) end love.graphics.setScissor() love.graphics.print(">", 6, h - 27) local input_prefix = _Debug.input:sub(1, _Debug.inputMarker) local input_prefix_width = _Debug.Font:getWidth(input_prefix) local autocomplete_width = 0 local input_suffix = _Debug.input:sub(_Debug.inputMarker + 1) if #_Debug.Proposals > 0 then autocomplete_width = _Debug.Font:getWidth(_Debug.Proposals[_Debug.proposaltoenter]) local proposal_prefix_width = _Debug.Font:getWidth(_Debug.Proposal_String) love.graphics.setColor(127, 127, 127) love.graphics.print(_Debug.Proposals[_Debug.proposaltoenter], 20 + input_prefix_width, h - 27) love.graphics.setColor(70, 70, 70) for i = math.max(_Debug.proposaltoenter - 1, 1), math.min(_Debug.proposaltoenter + 1, #_Debug.Proposals) do if i ~= _Debug.proposaltoenter then local index = i - _Debug.proposaltoenter love.graphics.print(_Debug.Proposal_String .. _Debug.Proposals[i], 20 + input_prefix_width - proposal_prefix_width, h - 27 - (fontSize - 1) * index) end end love.graphics.setColor(255, 255, 255) end if _Debug.drawTick then love.graphics.print("_", 20 + input_prefix_width, h - 27) end love.graphics.print(input_prefix, 20, h - 27) love.graphics.print(input_suffix, 20 + input_prefix_width + autocomplete_width, h - 27) if (#_Debug.order - _Debug.longestOffset > _Debug.lastRows - 1) then love.graphics.setFont(_Debug.BigFont) love.graphics.print("...", w - 30, h - 30) end love.graphics.setColor(r, g, b, a) if font then love.graphics.setFont(font) end _Debug.lastCut = cutY _Debug.lastH = h love.graphics.pop() end --Handle Mousepresses _Debug.handleMouse = function(a, b, c) if c == "wd" and _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = _Debug.orderOffset + 1 if _Debug.orderOffset > _Debug.longestOffset then _Debug.longestOffset = _Debug.orderOffset end end if c == "wu" and _Debug.orderOffset > 0 then _Debug.orderOffset = _Debug.orderOffset - 1 end if c == "m" and love.keyboard.isDown('lctrl') and _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = #_Debug.order - _Debug.lastRows + 1 end end --Process Keypresses _Debug.keyConvert = function(key) if string.len(key)==1 then -- No special characters. _Debug.inputMarker = _Debug.inputMarker + 1 _Debug.tick = 0 _Debug.drawTick = false return key elseif key == "left" then if _Debug.inputMarker > 0 then _Debug.inputMarker = _Debug.inputMarker - 1 _Debug.tick = 0 _Debug.drawTick = false end elseif key == "right" then if _Debug.inputMarker < #_Debug.input then _Debug.inputMarker = _Debug.inputMarker + 1 _Debug.tick = 0 _Debug.drawTick = false end elseif key == "up" then if #_Debug.Proposals > 0 and not love.keyboard.isDown('lshift', 'rshift') then _Debug.proposaltoenter = _Debug.proposaltoenter % #_Debug.Proposals + 1 _Debug.resetProposals = false else if _Debug.historyIndex > 1 then if _Debug.historyIndex == #_Debug.history then _Debug.history[_Debug.historyIndex] = _Debug.input end _Debug.historyIndex = _Debug.historyIndex - 1 _Debug.input = _Debug.history[_Debug.historyIndex] _Debug.inputMarker = #_Debug.input _Debug.tick = 0 _Debug.drawTick = false end end elseif key == "down" then if #_Debug.Proposals > 0 and not love.keyboard.isDown('lshift', 'rshift') then _Debug.proposaltoenter = (_Debug.proposaltoenter - 2) % #_Debug.Proposals + 1 _Debug.resetProposals = false else if _Debug.historyIndex < #_Debug.history then _Debug.historyIndex = _Debug.historyIndex + 1 _Debug.input = _Debug.history[_Debug.historyIndex] _Debug.inputMarker = #_Debug.input _Debug.tick = 0 _Debug.drawTick = false end end elseif key == "backspace" then local suffix = _Debug.input:sub(_Debug.inputMarker + 1, #_Debug.input) if _Debug.inputMarker == 0 then --Keep the input from copying itself suffix = "" end _Debug.input = _Debug.input:sub(1, _Debug.inputMarker - 1) .. suffix if _Debug.inputMarker > 0 then _Debug.inputMarker = _Debug.inputMarker - 1 _Debug.tick = 0 _Debug.drawTick = false end elseif key == 'f5' then _Debug.liveDo=true elseif key == "return" then if _Debug.input == 'clear' then --Clears the console _Debug.history[#_Debug.history] = _Debug.input table.insert(_Debug.history, '') _Debug.historyIndex = #_Debug.history _Debug.errors = {} _Debug.prints = {} _Debug.order = {} _Debug.orderOffset = 0 _Debug.longestOffset = 0 _Debug.lastH = nil _Debug.lastCut = nil _Debug.lastRows = 1 _Debug.input = "" _Debug.inputMarker = 0 return end local liveflag,prevfile,prevmod if string.find(_Debug.input,'_DebugSettings.LiveFile') then -- Saving previouse live data if changed. prevfile = _DebugSettings.LiveFile prevmod = _Debug.liveLastModified liveflag=true end --Execute Script print("> " .. _Debug.input) _Debug.history[#_Debug.history] = _Debug.input table.insert(_Debug.history, '') _Debug.historyIndex = #_Debug.history local f, err = loadstring(_Debug.input) if f then --f = xpcall(f,_Debug.handleError) f, err = pcall(f) end if not f then local sindex = 16 + #_Debug.input if sindex > 63 then sindex = 67 end _Debug.handleError(err) end _Debug.input = "" _Debug.inputMarker = 0 if _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = #_Debug.order - _Debug.lastRows + 1 end _Debug.tick = 0 _Debug.drawTick = false -- if liveflag then -- Setting up lastModified for the new live file(s) if changed if type(_DebugSettings.LiveFile) == 'table' then _Debug.liveLastModified={} for i = 1, #_DebugSettings.LiveFile do --Setting up lastModified for live files if not love.filesystem.exists(_DebugSettings.LiveFile[i]) then --if the file's not found then the live variables are reset _Debug.handleError('_DebugSettings.LiveFile: Index '..i..' file "'.._DebugSettings.LiveFile[i]..'" was not found.') _DebugSettings.LiveFile = prevfile _Debug.liveLastModified = prevmod return end _Debug.liveLastModified[i] = love.filesystem.getLastModified(_DebugSettings.LiveFile[i]) end else if love.filesystem.exists(_DebugSettings.LiveFile) then _Debug.liveLastModified = love.filesystem.getLastModified(_DebugSettings.LiveFile) else _Debug.handleError('_DebugSettings.LiveFile: File "'.._DebugSettings.LiveFile..'" was not found.') _DebugSettings.LiveFile = prevfile _Debug.liveLastModified = prevmod end end end elseif key == "home" then _Debug.inputMarker = 0 _Debug.tick = 0 _Debug.drawTick = false elseif key == "end" then _Debug.inputMarker = #_Debug.input _Debug.tick = 0 _Debug.drawTick = false elseif key == "tab" and #_Debug.Proposals > 0 then _Debug.input = _Debug.input:sub(1, _Debug.inputMarker) .. _Debug.Proposals[_Debug.proposaltoenter] .. _Debug.input:sub(_Debug.inputMarker + 1) _Debug.inputMarker = _Debug.inputMarker + #_Debug.Proposals[_Debug.proposaltoenter] _Debug.tick = 0 _Debug.drawTick = false else _Debug.resetProposals = false end end local _kwList = {'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'} _Debug.updateProposals = function(Table) local str = _Debug.Proposal_String local len = #str _Debug.Proposals = {} if Table == _G and str == '' then return end for k, v in pairs(Table) do if type(k) == 'string' and k:match '[_a-zA-Z][_a-zA-Z0-9]*' then if k:sub(1, len) == str then table.insert(_Debug.Proposals, k:sub(len + 1, #k)) end end end if Table == _G then for i, kw in pairs(_kwList) do if kw:sub(1, len) == str then table.insert(_Debug.Proposals, kw:sub(len + 1, #kw)) end end end _Debug.proposaltoenter = 2 if #_Debug.Proposals < 2 then _Debug.proposaltoenter = 1 end end _Debug.checkChars = function(str, chars) for i = 1, #str do local char = str:sub(i, i) local match = false for x = 1, #chars do local char2 = chars:sub(x, x) if char == char2 then match = true end end if match == false then return false end end return true end _Debug.findLocation = function(str) local name local path = {} local str, dot, lastname = str:match '(.-)%s*([.:]?)%s*([_a-zA-Z]?[_a-zA-Z0-9]*)$' while dot ~= '' do str, dot, name = str:match '(.-)%s*(%.?)%s*([_a-zA-Z][_a-zA-Z0-9]*)$' if not str then break end path[#path + 1] = name end local curTable = _G for i = #path, 1, -1 do curTable = rawget(curTable, path[i]) if type(curTable) ~= 'table' then _Debug.ProposalLocation = _G _Debug.Proposal_String = '' return end end _Debug.ProposalLocation = curTable _Debug.Proposal_String = lastname end --Handle Keypresses _Debug.handleKey = function(a) local activekey = love.system.getOS()~='Android' and (_lovedebugpresskey or "f8") or 'menu' if a == activekey then if love.keyboard.isDown("lshift", "rshift", "lctrl", "rctrl") then --Support for both Shift and CTRL _Debug.drawOverlay = not _Debug.drawOverlay --Toggle end elseif _Debug.drawOverlay then if love.keyboard.isDown('lctrl') then if a:lower()=='v' and #love.system.getClipboardText()>0 then local clipboard=love.system.getClipboardText() local text={} for char in string.gmatch(clipboard,".") do text[#text+1]=char end _Debug.handleVirtualKey(text) elseif a:lower()=='c' then love.system.setClipboardText(_Debug.input) return else _Debug.handleVirtualKey(a) if not _Debug.trackKeys[a] then _Debug.trackKeys[a] = { time = _Debug.keyRepeatInterval - _Debug.keyRepeatDelay} end end else _Debug.handleVirtualKey(a) if not _Debug.trackKeys[a] then _Debug.trackKeys[a] = { time = _Debug.keyRepeatInterval - _Debug.keyRepeatDelay} end end end end --Handle Virtual Keypresses _Debug.handleVirtualKey = function(a) if type(a) == 'string' then _Debug.resetProposals = true local add = _Debug.keyConvert(a) or '' --Needed for backspace, do NOT optimize local suffix = _Debug.input:sub(_Debug.inputMarker, (#_Debug.input >= _Debug.inputMarker) and #_Debug.input or _Debug.inputMarker + 1) if _Debug.inputMarker == 0 then --Keep the input from copying itself suffix = "" end _Debug.input = _Debug.input:sub(0, _Debug.inputMarker - 1) .. add .. suffix if _Debug.resetProposals then if _Debug.inputMarker == 0 or _Debug.input:sub(_Debug.inputMarker + 1, _Debug.inputMarker + 1):find('[0-9a-zA-Z_]') then _Debug.ProposalLocation = _G _Debug.Proposal_String = '' else _Debug.findLocation(_Debug.input:sub(1, _Debug.inputMarker)) end _Debug.updateProposals(_Debug.ProposalLocation) end else for i=1,#a do _Debug.resetProposals = true _Debug.inputMarker = _Debug.inputMarker + 1 _Debug.tick = 0 _Debug.drawTick = false _Debug.handlePast(a[i]) end if not _Debug.trackKeys[a] then _Debug.trackKeys[a] = { time = _Debug.keyRepeatInterval - _Debug.keyRepeatDelay} end end end _Debug.handlePast = function(add) local suffix = _Debug.input:sub(_Debug.inputMarker, (#_Debug.input >= _Debug.inputMarker) and #_Debug.input or _Debug.inputMarker + 1) if _Debug.inputMarker == 0 then --Keep the input from copying itself suffix = "" end _Debug.input = _Debug.input:sub(0, _Debug.inputMarker - 1) .. add .. suffix if _Debug.resetProposals then if _Debug.inputMarker == 0 or _Debug.input:sub(_Debug.inputMarker + 1, _Debug.inputMarker + 1):find('[0-9a-zA-Z_]') then _Debug.ProposalLocation = _G _Debug.Proposal_String = '' else _Debug.findLocation(_Debug.input:sub(1, _Debug.inputMarker)) end _Debug.updateProposals(_Debug.ProposalLocation) end end --Reloads the Code, update() and load() _Debug.hotSwapUpdate = function(dt,file) local file = file or _DebugSettings.LiveFile local output, ok, err, loadok, updateok success, chunk = pcall(love.filesystem.load, file) if not success then _Debug.handleError(tostring(chunk)) output = chunk .. '\n' end ok,err = xpcall(chunk, _Debug.handleError) if ok then print("'"..file.."' Reloaded.") else print('Something went wrong while trying to update file: '..file) end if _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = #_Debug.order - _Debug.lastRows + 1 end if file == 'main' then --so it only updates love.update() once updateok,err=pcall(love.update,dt) end end --Reloads the code, love.load() _Debug.hotSwapLoad = function() local loadok,err=xpcall(love.load,_Debug.handleError) if loadok then print("'love.load()' Reloaded.") end if _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = #_Debug.order - _Debug.lastRows + 1 end end --Reloads the code, draw(), I don't think this is needed.. _Debug.hotSwapDraw = function() local drawok,err drawok,err = xpcall(love.draw,_Debug.handleError) end _Debug.liveCheckLastModified = function(table1,table2) if type(table1) == 'string' then if love.filesystem.getLastModified(table1) ~= table2 then return true end return false end for i,v in ipairs(table1) do if love.filesystem.getLastModified(v) ~= table2[i] then return true end end return false end --Modded version of original love.run _G["love"].run = function() if love.math then love.math.setRandomSeed(os.time()) end if love.event then love.event.pump() end if love.load then xpcall(love.load, _Debug.handleError) end if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for e,a,b,c,d in love.event.poll() do if e == "quit" then local quit = false if love.quit then xpcall(function() quit = love.quit() end, _Debug.handleError) end if not quit then if love.audio then love.audio.stop() end return end end local skipEvent = false if e == "textinput" then --Keypress skipEvent = true _Debug.handleKey(a) if not _Debug.drawOverlay then if love.textinput then love.textinput(a) end end end if e == "keypressed" then --Keypress skipEvent = true if string.len(a)>=2 or (love.keyboard.isDown('lctrl') and (a == 'c' or a == 'v')) then _Debug.handleKey(a) end if not _Debug.drawOverlay then if love.keypressed then love.keypressed(a,b) end end end if e == "keyreleased" then --Keyrelease skipEvent = true if not _Debug.drawOverlay then if love.keyreleased then love.keyreleased(a, b) end end end if e == "mousepressed" and _Debug.drawOverlay then --Mousepress skipEvent = true _Debug.handleMouse(a, b, c) end if not skipEvent then xpcall(function() love.handlers[e](a,b,c,d) end, _Debug.handleError) end end end if love.timer then love.timer.step() dt = love.timer.getDelta() _Debug.onTopUpdate(dt) end _Debug.tick = _Debug.tick - dt if _Debug.tick <= 0 then _Debug.tick = _Debug.tickTime + _Debug.tick _Debug.drawTick = not _Debug.drawTick end if _Debug.drawOverlay then for key, d in pairs(_Debug.trackKeys) do if type(key) == 'string' then if love.keyboard.isDown(key) then d.time = d.time + dt if d.time >= _Debug.keyRepeatInterval then d.time = 0 _Debug.handleVirtualKey(key) end else _Debug.trackKeys[key] = nil end else if love.keyboard.isDown('v') and love.keyboard.isDown('lctrl') then d.time = d.time + dt if d.time >= _Debug.keyRepeatInterval then d.time = 0 _Debug.handleVirtualKey(key) end else _Debug.trackKeys[key] = nil end end end -- Call love.update() if we are not to halt program execution if _DebugSettings.HaltExecution == false then xpcall(function() love.update(dt) end, _Debug.handleError) end -- Auto scroll the console if AutoScroll == true if _DebugSettings.AutoScroll == true then if _Debug.orderOffset < #_Debug.order - _Debug.lastRows + 1 then _Debug.orderOffset = #_Debug.order - _Debug.lastRows + 1 end end end if love.update and not _Debug.drawOverlay then if _DebugSettings.LiveAuto and _Debug.liveCheckLastModified(_DebugSettings.LiveFile,_Debug.liveLastModified) then if type(_DebugSettings.LiveFile) == 'table' then for i=1,#_DebugSettings.LiveFile do if love.filesystem.getLastModified(_DebugSettings.LiveFile[i]) ~= _Debug.liveLastModified[i] then _Debug.hotSwapUpdate(dt,_DebugSettings.LiveFile[i]) _Debug.liveLastModified[i] = love.filesystem.getLastModified(_DebugSettings.LiveFile[i]) end end if _DebugSettings.LiveReset then _Debug.hotSwapLoad() end else _Debug.hotSwapUpdate(dt,_DebugSettings.LiveFile) _Debug.liveLastModified = love.filesystem.getLastModified(_DebugSettings.LiveFile) if _DebugSettings.LiveReset then _Debug.hotSwapLoad() end end else xpcall(function() love.update(dt) end, _Debug.handleError) end elseif love.update and (_Debug.liveDo or (_DebugSettings.LiveAuto and _Debug.liveCheckLastModified(_DebugSettings.LiveFile,_Debug.liveLastModified))) then if type(_DebugSettings.LiveFile) == 'table' then for i=1,#_DebugSettings.LiveFile do if (_DebugSettings.LiveAuto and love.filesystem.getLastModified(_DebugSettings.LiveFile[i]) ~= _Debug.liveLastModified[i]) or _Debug.liveDo then _Debug.hotSwapUpdate(dt,_DebugSettings.LiveFile[i]) _Debug.liveLastModified[i] = love.filesystem.getLastModified(_DebugSettings.LiveFile[i]) end end if _DebugSettings.LiveReset then _Debug.hotSwapLoad() end else _Debug.hotSwapUpdate(dt,_DebugSettings.LiveFile) if _DebugSettings.LiveReset then _Debug.hotSwapLoad() end _Debug.liveLastModified = love.filesystem.getLastModified(_DebugSettings.LiveFile) end end -- will pass 0 if love.timer is disabled if love.window and love.graphics and love.window.isCreated() then love.graphics.clear() love.graphics.origin() if love.draw then if _Debug.liveDo then _Debug.hotSwapDraw() _Debug.liveDo=false end xpcall(love.draw, _Debug.handleError) end if _DebugSettings.DrawOnTop then _Debug.onTop() end if _Debug.drawOverlay then _Debug.overlay() end love.graphics.present() end if love.timer then love.timer.sleep(0.001) end end end
mit
crabman77/minetest-minetestforfun-server
mods/coloredwood/stick.lua
8
4317
-- Sticks portion of Colored Wood mod by Vanessa Ezekowitz ~~ 2012-07-17 -- based on my unified dyes modding template. -- -- License: WTFPL local colored_block_modname = "coloredwood" local colored_block_description = "Stick" for shade = 1, 3 do local shadename = coloredwood.shades[shade] local shadename2 = coloredwood.shades2[shade] for hue = 1, 12 do local huename = coloredwood.hues[hue] local huename2 = coloredwood.hues2[hue] local colorname = colored_block_modname..":stick_"..shadename..huename local pngname = colored_block_modname.."_stick_"..shadename..huename..".png" local itemdesc = shadename2..huename2..colored_block_description local woodname = colored_block_modname..":wood_"..shadename..huename local s50colorname = colored_block_modname..":stick_"..shadename..huename.."_s50" local s50pngname = colored_block_modname.."_stick_"..shadename..huename.."_s50.png" local s50itemdesc = shadename2..huename2..colored_block_description.." (50% Saturation)" local s50woodname = colored_block_modname..":wood_"..shadename..huename.."_s50" minetest.register_craft({ type = "fuel", recipe = colorname, burntime = 7, }) minetest.register_craft({ type = "fuel", recipe = s50colorname, burntime = 7, }) minetest.register_craftitem(colorname, { description = itemdesc, inventory_image = pngname, groups = { coloredsticks=1, stick=1 } }) minetest.register_craftitem(s50colorname, { description = s50itemdesc, inventory_image = s50pngname, groups = { coloredsticks=1, stick=1 } }) minetest.register_craft( { type = "shapeless", output = colorname.." 4", recipe = { woodname } }) minetest.register_craft( { type = "shapeless", output = s50colorname.." 4", recipe = { s50woodname } }) end end -- Generate the "light" shades separately, since they don"t have a low-sat version. for hue = 1, 12 do local huename = coloredwood.hues[hue] local huename2 = coloredwood.hues2[hue] local colorname = colored_block_modname..":stick_light_"..huename local pngname = colored_block_modname.."_stick_light_"..huename..".png" local itemdesc = "Light "..huename2..colored_block_description local woodname = colored_block_modname..":wood_light_"..huename minetest.register_craftitem(colorname, { description = itemdesc, inventory_image = pngname, groups = { coloredsticks=1, stick=1 } }) minetest.register_craft({ type = "fuel", recipe = colorname, burntime = 7, }) minetest.register_craft( { type = "shapeless", output = colorname.." 4", recipe = { woodname } }) end -- ============================================================ -- The 5 levels of greyscale. -- -- Oficially these are 0, 25, 50, 75, and 100% relative to white, -- but in practice, they"re actually 7.5%, 25%, 50%, 75%, and 95%. -- (otherwise black and white would wash out). for grey = 1,5 do local greyname = coloredwood.greys[grey] local greyname2 = coloredwood.greys2[grey] local greyshadename = colored_block_modname..":stick_"..greyname local pngname = colored_block_modname.."_stick_"..greyname..".png" local itemdesc = greyname2..colored_block_description local greywoodname = colored_block_modname..":wood_"..greyname minetest.register_craftitem(greyshadename, { description = itemdesc, inventory_image = pngname, groups = { coloredsticks=1, stick=1 } }) minetest.register_craft({ type = "fuel", recipe = greyshadename, burntime = 7, }) minetest.register_craft( { type = "shapeless", output = greyshadename.." 4", recipe = { greywoodname } }) end -- ==================================================================== -- This recipe causes all colored sticks to be usable to craft ladders. minetest.register_craft({ output = "default:ladder 2" , recipe = { {"group:coloredsticks", "" , "group:coloredsticks" }, {"group:coloredsticks", "group:coloredsticks", "group:coloredsticks" }, {"group:coloredsticks", "" , "group:coloredsticks" } } })
unlicense
libcg/gSquare
game/levels/medium3.lua
1
1608
function getInfo() -- Title local title = { "Day 13.\n\nKeep it simple, stupid", "Jour 13.\n\nPensez simplement" } levelText(title[getLanguageID()+1]) end function setGame() -- Music setMusic("./audio/c418-heyhey.mp3") -- Player varPlayerX(16*6) varPlayerY(16*4) -- Gravity varGravityDir(2) end function setLevel() -- Temporary level matrix local lvl_w, lvl_h = 17, 16 local lvl = {{0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,9,1,1,1,1,0,0,0,0,0,0}, {0,0,0,0,0,0,1,0,4,0,1,1,0,0,0,0,0}, {0,0,0,0,0,1,0,0,4,0,4,1,1,0,0,0,0}, {0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0}, {4,4,4,4,1,0,0,0,0,0,0,0,1,2,2,4,2}, {0,0,0,0,1,0,0,4,0,0,4,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,2,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,2,0,0,2,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,1,c,1,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0}} -- Reset level initObject() -- Init objects using the matrix for i=1,lvl_w do for j=1,lvl_h do if lvl[j][i]>0 then createObjectAligned(16*(i-1),16*(j-1),0,0,lvl[j][i],16) end end end -- Finish createObjectAligned(16*9,16*5,0,0,b,16) objectText("./levels/medium4.lua") -- Init checkpoints createObjectAligned(16*8,16*13,0,0,7,16) local t1 = { "OK, let's go inside now!", "OK, je vais à l'intérieur!" } objectText(t1[getLanguageID()+1]) end
gpl-3.0
minetest-australopithecus/minetest-australopithecus-utils
mods/utils/rotationutil.lua
2
6769
--[[ Copyright (c) 2015, Robert 'Bobby' Zenz 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. 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. --]] --- Various functions for rotating nodes. -- -- The internal mechanics of Minetest are as follows: It uses the facedir value -- to apply an rotation. It is value with the minimum of 0 (no rotation) to -- the maximum of 23 (1 0 1 1 1). It consists of two parts, the lower two bits -- are the amount of rotation applied: -- -- Bits Value Description -- 0 0 0 No rotation -- 0 1 1 90 degrees (sign depending on axis, + for z+ x- y-) -- 1 0 2 180 degrees -- 1 1 3 -90 degrees (sign depending on axis, + for z- x+ y+) -- -- These values correspond to the ROT_* constants. -- -- The upper three bits are the axis that is used: -- -- Bits Value Shifted Description -- 0 0 0 0 0 y+, no rotation -- 0 0 1 1 4 z+, 90 degrees clockwise around x -- 0 1 0 2 8 z-, 90 degrees counter-clockwise around x -- 0 1 1 3 12 x+, 90 degrees counter-clockwise around z -- 1 0 0 4 16 x-, 90 degrees clockwise around z -- 1 0 1 5 20 y-, 180 degrees counter-clockwise around x -- -- These values correspond to the POS_* and NEG_* constants. -- -- The rotation is a two step process, first the rotation of the axis/upper -- three bits are applied, after that the rotation/lower two bits. -- -- See the mapnode.cpp/transformNodeBox function for even more details. rotationutil = { --- The negative X Axis. Will rotate the node around the Z axis by -- 90 degrees clockwise before the additional rotation is applied. -- -- Minetest internal it has the value 4, within facedir it is 16 (1 0 0 R R). NEG_X = 16, --- The negative Z Axis. Will rotate the node around the X axis by -- 90 degrees counter-clockwise before the additional rotation is applied. -- -- Minetest internal it has the value 2, within facedir it is 8 (0 1 0 R R). NEG_Z = 8, --- The negative Y Axis. Will rotate the node around the Z axis by -- 180 degrees counter-clockwise before the additional rotation is applied. -- -- Minetest internal it has the value 5, within the bitmask of facedir it -- is 20 (1 0 1 R R). NEG_Y = 20, --- The positive X Axis. Will rotate the node around the Z axis by -- 90 degrees counter-clockwise before the additional rotation is applied. -- -- Minetest internal it has the value 3, within facedir it is 12 (0 1 1 R R). POS_X = 12, --- The positive Y Axis. Will not rotate the node before the additional -- rotation is applied. -- -- Minetest internal it has the value 0, within of facedir it is 0 (0 0 0 R R). POS_Y = 0, --- The positive Z Axis. Will rotate the node around the X axis by -- 90 degrees clockwise before the additional rotation is applied. -- -- Minetest internal it has the value 1, within facedir it is 4 (0 0 1 R R). POS_Z = 4, --- No rotation. ROT_0 = 0, --- Rotation 90 degrees, sign depends on the axis. ROT_90 = 1, --- Rotation 180 degrees. ROT_180 = 2, --- Rotation 270/-90 degrees, sign depends on the axis. ROT_270 = 3 } --- Returns the decremented rotation, so given rotation - 90 degrees. -- -- @param rotation The rotation to decrement. -- @return The decremented rotation, or the given value if it was not valid. function rotationutil.decrement(rotation) if rotation == rotationutil.ROT_0 then return rotationutil.ROT_270 elseif rotation == rotationutil.ROT_90 then return rotationutil.ROT_0 elseif rotation == rotationutil.ROT_180 then return rotationutil.ROT_90 elseif rotation == rotationutil.ROT_270 then return rotationutil.ROT_180 end return rotation end --- Creates the facedir value from the given axis and rotation. -- -- @param axis The axis, one of the POS_* or NEG_* constants. -- @param rotation The rotation, one of the ROT_* constants. -- @return The facedir value. function rotationutil.facedir(axis, rotation) return axis + rotation end --- Returns the incremented rotation, so given rotation + 90 degrees. -- -- @param rotation The rotation to increment. -- @return The incremented rotation, or the given value if it was not valid. function rotationutil.increment(rotation) if rotation == rotationutil.ROT_0 then return rotationutil.ROT_90 elseif rotation == rotationutil.ROT_90 then return rotationutil.ROT_180 elseif rotation == rotationutil.ROT_180 then return rotationutil.ROT_270 elseif rotation == rotationutil.ROT_270 then return rotationutil.ROT_0 end return rotation end --- Inverts the given axis or rotation. -- @param axis_or_rotation The axis or rotation, one of the POS_*, NEG_* or -- ROT_* constants. -- @return The inverted value, or the given value if it was not valid. function rotationutil.invert(axis_or_rotation) if axis_or_rotation == rotationutil.NEG_X then return rotationutil.POS_X elseif axis_or_rotation == rotationutil.NEG_Y then return rotationutil.POS_Y elseif axis_or_rotation == rotationutil.NEG_Z then return rotationutil.POS_Z elseif axis_or_rotation == rotationutil.POS_X then return rotationutil.NEG_X elseif axis_or_rotation == rotationutil.POS_Y then return rotationutil.NEG_Y elseif axis_or_rotation == rotationutil.POS_Y then return rotationutil.NEG_Z end if axis_or_rotation == rotationutil.ROT_0 then return rotationutil.ROT_180 elseif axis_or_rotation == rotationutil.ROT_90 then return rotationutil.ROT_270 elseif axis_or_rotation == rotationutil.ROT_180 then return rotationutil.ROT_0 elseif axis_or_rotation == rotationutil.ROT_270 then return rotationutil.ROT_90 end return axis_or_rotation end
bsd-2-clause
kitala1/darkstar
scripts/globals/mobskills/Dispelling_Wind.lua
7
1035
--------------------------------------------- -- Dispelling Wind -- -- Description: Dispels two effects from targets in an area of effect. -- Type: Enfeebling -- Utsusemi/Blink absorb: Ignores shadows -- Range: 10' radial -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local dis1 = target:dispelStatusEffect(); local dis2 = target:dispelStatusEffect(); if(dis1 ~= EFFECT_NONE and dis2 ~= EFFECT_NONE) then skill:setMsg(MSG_DISAPPEAR_NUM); return 2; elseif(dis1 ~= EFFECT_NONE or dis2 ~= EFFECT_NONE) then -- dispeled only one skill:setMsg(MSG_DISAPPEAR_NUM); return 1; else skill:setMsg(MSG_NO_EFFECT); -- no effect end return 0; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Qulun_Dome/npcs/_440.lua
18
1499
----------------------------------- -- Area: Qulun Dome -- NPC: Door -- Involved in Mission: Magicite -- @pos 60 24 -2 148 ----------------------------------- package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Qulun_Dome/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(CORUSCANT_ROSARY) and player:hasKeyItem(BLACK_MATINEE_NECKLACE)) then if(player:getZPos() < -7.2) then player:startEvent(0x0033); else player:startEvent(0x0032); end else player:messageSpecial(IT_SEEMS_TO_BE_LOCKED_BY_POWERFUL_MAGIC); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if((csid == 0x0032 or csid == 0x0033) and option == 1) then player:messageSpecial(THE_3_ITEMS_GLOW_FAINTLY,SILVER_BELL,CORUSCANT_ROSARY,BLACK_MATINEE_NECKLACE); end end;
gpl-3.0
ZenityRTS/Zenity
libs/chonsole/exts/lobby.lua
1
5819
-- Do not load this in gadgets if not WG then return end -- disable in case there's no liblobby installed if not WG.LibLobby or not WG.LibLobby.lobby then Spring.Log("Chonsole", LOG.WARNING, i18n("liblobby_not_installed", {default = "liblobby is not installed. Lobby support disabled."})) return end Spring.Log("Chonsole", LOG.NOTICE, i18n("liblobby_is_installed", {default = "liblobby is installed. Lobby support enabled."})) local channelColor = "\204\153\1" local consoles = {} -- ID -> name mapping local lobby = WG.LibLobby.lobby lobby:AddListener("OnJoin", function(listener, chanName) local id = 1 while true do if not consoles[id] then consoles[id] = chanName Spring.Echo("\255" .. channelColor .. i18n("joined", {default = "Joined"}) .. " [" .. tostring(id) .. ". " .. chanName .. "]") break end id = id + 1 end end ) lobby:AddListener("OnJoined", function(listener, chanName, userName) for id, name in pairs(consoles) do if name == chanName then consoles[id] = chanName Spring.Echo("\255" .. channelColor .. userName .. " " .. i18n("user_joined", {default = "joined"}) .. " [" .. tostring(id) .. ". " .. chanName .. "]") break end end end ) lobby:AddListener("OnLeft", function(listener, chanName, userName) for id, name in pairs(consoles) do if name == chanName then consoles[id] = chanName Spring.Echo("\255" .. channelColor .. userName .. " " .. i18n("user_left", {default = "left"}) .. " [" .. tostring(id) .. ". " .. chanName .. "]") break end end end ) lobby:AddListener("OnSaid", function(listener, chanName, userName, message) for id, name in pairs(consoles) do if name == chanName then -- print channel message local msg = "\255" .. channelColor .. "[" .. tostring(id) .. ". " .. chanName .. "] <" .. userName .. "> " .. message .. "\b" Spring.Echo(msg) break end end end ) lobby:AddListener("OnAccepted", function(listener) Spring.Echo("\255" .. channelColor .. i18n("connected_server", {default="Connected to server."}) .. "\b") end ) lobby:AddListener("OnDenied", function(listener, reason) Spring.Echo("\255" .. channelColor .. i18n("failed_connect", {default="Failed connecting to server: "}) .. reason .. "\b") end ) lobby:AddListener("OnDisconnected", function(listener) consoles = {} Spring.Echo("\255" .. channelColor .. i18n("disconnected_server", {default="Disconnected from server."})) if GetCurrentContext().name == "channel" then ResetCurrentContext() end -- check if we'll try to reconnect if lobby:GetConnectionStatus() == "disconnected" then -- FIXME: make this variable part of the API local delay = lobby.reconnectionDelay Spring.Echo("\255" .. channelColor .. i18n("announce_reconnect", {default="Attempting reconnect in %{delay} seconds.", delay=delay}) .. "\b") end end ) commands = { { command = "login", description = i18n("login_desc", {default = "Login to Spring Lobby"}), exec = function(command, cmdParts) Spring.Echo("\255" .. channelColor .. i18n("connecting_server", {default="Connecting to server..."})) lobby:AddListener("OnTASServer", function() lobby:Login(cmdParts[2], cmdParts[3], 3) end) lobby:Connect("springrts.com", 8200) end, }, { command = "logout", description = i18n("logout_desc", {default="Logout from Spring Lobby"}), exec = function(command, cmdParts) if lobby:GetConnectionStatus() ~= "connected" then -- No need to print out an error message to the user, since it doesn't make any sense to logout while not connected anyway return end lobby:Exit("Leaving") end, }, { command = "join", description = i18n("join_desc", {default="Join a channel"}), exec = function(command, cmdParts) if lobby:GetConnectionStatus() ~= "connected" then Spring.Echo("\255" .. channelColor .. i18n("login_first", {default="Cannot join a channel while disconnected. Login first."}) .. "\b") return end lobby:Join(cmdParts[2], cmdParts[3]) end, }, { command = "leave", description = i18n("leave_desc", {default="Leave a channel"}), exec = function(command, cmdParts) if lobby:GetConnectionStatus() ~= "connected" then -- No need to print out an error message to the user, since it doesn't make any sense to leave channels while not connected anyway return end local chanName = cmdParts[2] local currentContext = GetCurrentContext() if chanName == nil or chanName:trim() == "" then if currentContext.name == "channel" then chanName = consoles[currentContext.id] else return end end -- TODO: should probably use a listener instead but need to implement it for id, name in pairs(consoles) do if name == chanName then Spring.Echo("\255" .. channelColor .. i18n("left", {default="Left"}) .. " [" .. tostring(id) .. ". " .. chanName .. "]") if currentContext.name == "channel" and currentContext.id == id then ResetCurrentContext() end consoles[id] = nil break end end lobby:Leave(chanName) end, }, -- TODO: support for private chat, /ignore, /friend, /friendlist, /channelist, /ignorelist -- TODO: preserve channel list. This may belong to liblobby instead. -- TODO: battleroom chat -- TODO: battleroom join/part messages -- TODO: friends coming online/offline } context = { { name = "channel", parse = function(txt) if tonumber(txt:trim():sub(2)) ~= nil and txt:sub(#txt, #txt) == " " then local id = tonumber(txt:trim():sub(2)) if consoles[id] ~= nil then return true, { display = "\255" .. channelColor .. "[" .. tostring(id) .. ". " .. consoles[id] .. "]\b", name = "channel", id = id, persist = true } end end end, exec = function(str, context) lobby:Say(consoles[context.id], str) end }, }
gpl-2.0
kitala1/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Icon_Prototype.lua
17
1387
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Icon Prototype ----------------------------------- package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob,target) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- Time Bonus: 043 if(mobID == 17330814 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(30); mob:addInBattlefieldList(); -- HP Bonus: 052 elseif(mobID == 17330533) then killer:restoreHP(2000); killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); -- HP Bonus: 073 elseif(mobID == 17330843) then killer:restoreMP(2000); killer:messageBasic(025,(killer:getMaxMP()-killer:getMP())); end end;
gpl-3.0
JavidTeam/TeleJavid
libs/feedparser.lua
543
11955
local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...") local XMLElement = (loadfile "./libs/XMLElement.lua")() local dateparser = (loadfile "./libs/dateparser.lua")() local URL = (loadfile "./libs/url.lua")() local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local pairs, ipairs = pairs, ipairs --- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker. -- see http://feedparser.org for details about the Universal Feed Parser local feedparser= { _DESCRIPTION = "RSS and Atom feed parser", _VERSION = "feedparser 0.71" } local blanky = XMLElement.new() --useful in a whole bunch of places local function resolve(url, base_url) return URL.absolute(base_url, url) end local function rebase(el, base_uri) local xml_base = el:getAttr('xml:base') if not xml_base then return base_uri end return resolve(xml_base, base_uri) end local function parse_entries(entries_el, format_str, base) local entries = {} for i, entry_el in ipairs(entries_el) do local entry = {enclosures={}, links={}, contributors={}} local entry_base = rebase(entry_el, base) for i, el in ipairs(entry_el:getChildren('*')) do local tag = el:getTag() local el_base = rebase(el, entry_base) --title if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever. entry.title=el:getText() --link(s) elseif format_str == 'rss' and tag=='link' then entry.link=resolve(el:getText(), el_base) tinsert(entry.links, {href=entry.link}) elseif (format_str=='atom' and tag == 'link') or (format_str == 'rss' and tag=='atom:link') then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri end tinsert(entry.links, link) if link.rel=='enclosure' then tinsert(entry.enclosures, { href=link.href, length=el:getAttr('length'), type=el:getAttr('type') }) end --rss enclosures elseif format_str == 'rss' and tag=='enclosure' then tinsert(entry.enclosures, { url=el:getAttr('url'), length=el:getAttr('length'), type=el:getAttr('type') }) --summary elseif (format_str=='atom' and tag=='summary') or (format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then entry.summary=el:getText() --TODO: summary_detail --content elseif (format_str=='atom' and tag=='content') or (format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then entry.content=el:getText() --TODO: content_detail --published elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or (format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then entry.published = el:getText() entry.published_parsed=dateparser.parse(entry.published) --updated elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or (format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then entry.updated=el:getText() entry.updated_parsed=dateparser.parse(entry.updated) elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then entry.created=el:getText() entry.created_parsed=dateparser.parse(entry.created) --id elseif (format_str =='atom' and tag=='id') or (format_str=='rss' and tag=='guid') then entry.id=resolve(el:getText(), el_base) -- this is a uri, right?... --author elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this? entry.author=(el:getChild('name') or el):getText() entry.author_detail={ name=entry.author } elseif format_str=='atom' and tag=='author' then entry.author=(el:getChild('name') or el):getText() entry.author_detail = { name=entry.author, email=(el:getChild('email') or blanky):getText() } local author_url = (el:getChild('url') or blanky):getText() if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end elseif tag=='category' or tag=='dc:subject' then --todo elseif tag=='source' then --todo end end --wrap up rss guid if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri end --wrap up entry.link for i, link in pairs(entry.links) do if link.rel=="alternate" or (not link.rel) or link.rel=="" then entry.link=link.href --already resolved. break end end if not entry.link and format_str=='rss' then entry.link=entry.id end tinsert(entries, entry) end return entries end local function atom_person_construct(person_el, base_uri) local dude ={ name= (person_el:getChild('name') or blanky):getText(), email=(person_el:getChild('email') or blanky):getText() } local url_el = person_el:getChild('url') if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end return dude end local function parse_atom(root, base_uri) local res = {} local feed = { links = {}, contributors={}, language = root:getAttr('lang') or root:getAttr('xml:lang') } local root_base = rebase(root, base_uri) res.feed=feed res.format='atom' local version=(root:getAttr('version') or ''):lower() if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10' elseif version=="0.3" then res.version='atom03' else res.version='atom' end for i, el in ipairs(root:getChildren('*')) do local tag = el:getTag() local el_base=rebase(el, root_base) if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then feed.title=el:getText() --sanitize! --todo: feed.title_detail --link stuff elseif tag=='link' then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) end tinsert(feed.links, link) --subtitle elseif tag == 'subtitle' then feed.subtitle=el:getText() --sanitize! elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() --sanitize! elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info elseif tag == 'info' then --whatever, nobody cared, anyway. feed.info = el:getText() --id elseif tag=='id' then feed.id=resolve(el:getText(), el_base) --this is a url, right?.,, --updated elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then feed.updated = el:getText() feed.updated_parsed=dateparser.parse(feed.updated) --author elseif tag=='author' or tag=='atom:author' then feed.author_detail=atom_person_construct(el, el_base) feed.author=feed.author_detail.name --contributors elseif tag=='contributor' or tag=='atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --icon elseif tag=='icon' then feed.icon=resolve(el:getText(), el_base) --logo elseif tag=='logo' then feed.logo=resolve(el:getText(), el_base) --language elseif tag=='language' or tag=='dc:language' then feed.language=feed.language or el:getText() --licence end end --feed.link (already resolved) for i, link in pairs(feed.links) do if link.rel=='alternate' or not link.rel or link.rel=='' then feed.link=link.href break end end res.entries=parse_entries(root:getChildren('entry'),'atom', root_base) return res end local function parse_rss(root, base_uri) local channel = root:getChild({'channel', 'rdf:channel'}) local channel_base = rebase(channel, base_uri) if not channel then return nil, "can't parse that." end local feed = {links = {}, contributors={}} local res = { feed=feed, format='rss', entries={} } --this isn't quite right at all. if root:getTag():lower()=='rdf:rdf' then res.version='rss10' else res.version='rss20' end for i, el in ipairs(channel:getChildren('*')) do local el_base=rebase(el, channel_base) local tag = el:getTag() if tag=='link' then feed.link=resolve(el:getText(), el_base) tinsert(feed.links, {href=feed.link}) --title elseif tag == 'title' or tag == 'dc:title' then feed.title=el:getText() --sanitize! --subtitle elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'dc:rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info (nobody cares...) elseif tag == 'feedburner:browserFriendly' then feed.info = el:getText() --updated elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then feed.updated = el:getText() feed.updated_parsed = dateparser.parse(feed.updated) --author elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then feed.author=tconcat(el:getChildren('text()')) feed.author_details={name=feed.author} elseif tag=='atom:author' then feed.author_details = atom_person_construct(el, el_base) feed.author = feed.author_details.name --contributors elseif tag == 'dc:contributor' then tinsert(feed.contributors, {name=el:getText()}) elseif tag == 'atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --image elseif tag=='image' or tag=='rdf:image' then feed.image={ title=el:getChild('title'):getText(), link=(el:getChild('link') or blanky):getText(), width=(el:getChild('width') or blanky):getText(), height=(el:getChild('height') or blanky):getText() } local url_el = el:getChild('url') if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end --language elseif tag=='language' or tag=='dc:language' then feed.language=el:getText() --licence --publisher --tags end end res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base) return res end --- parse feed xml -- @param xml_string feed xml, as a string -- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents -- @return table with parsed feed info, or nil, error_message on error. -- the format of the returned table is much like that on http://feedparser.org, with the major difference that -- dates are parsed into unixtime. Most other fields are very much the same. function feedparser.parse(xml_string, base_url) local lom, err = LOM.parse(xml_string) if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end local rootElement = XMLElement.new(lom) local root_tag = rootElement:getTag():lower() if root_tag=='rdf:rdf' or root_tag=='rss' then return parse_rss(rootElement, base_url) elseif root_tag=='feed' then return parse_atom(rootElement, base_url) else return nil, "unknown feed format" end end --for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3 if _VERSION:sub(-3) < "5.3" then _G.feedparser=feedparser end return feedparser
gpl-3.0
kitala1/darkstar
scripts/zones/Zeruhn_Mines/npcs/Makarim.lua
17
1511
----------------------------------- -- Area: Zeruhn Mines -- NPC: Makarim -- Involved In Mission: The Zeruhn Report -- @pos -58 8 -333 172 ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Zeruhn_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(BASTOK) == THE_ZERUHN_REPORT) then if(player:hasKeyItem(ZERUHN_REPORT)) then player:messageSpecial(MAKARIM_DIALOG_I); else player:startEvent(0x0079); end else player:startEvent(0x0068); 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 == 0x0079) then player:addKeyItem(ZERUHN_REPORT); player:messageSpecial(KEYITEM_OBTAINED,ZERUHN_REPORT); end end;
gpl-3.0
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ControlSlider.lua
3
4537
-------------------------------- -- @module ControlSlider -- @extend Control -------------------------------- -- @function [parent=#ControlSlider] getSelectedThumbSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#ControlSlider] locationFromTouch -- @param self -- @param #cc.Touch touch -- @return Vec2#Vec2 ret (return value: cc.Vec2) -------------------------------- -- @function [parent=#ControlSlider] setSelectedThumbSprite -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#ControlSlider] setProgressSprite -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#ControlSlider] getMaximumAllowedValue -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ControlSlider] getMinimumAllowedValue -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ControlSlider] getMinimumValue -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ControlSlider] setThumbSprite -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#ControlSlider] setMinimumValue -- @param self -- @param #float float -------------------------------- -- @function [parent=#ControlSlider] setMinimumAllowedValue -- @param self -- @param #float float -------------------------------- -- @function [parent=#ControlSlider] setEnabled -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ControlSlider] setValue -- @param self -- @param #float float -------------------------------- -- @function [parent=#ControlSlider] setMaximumValue -- @param self -- @param #float float -------------------------------- -- @function [parent=#ControlSlider] needsLayout -- @param self -------------------------------- -- @function [parent=#ControlSlider] getBackgroundSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- overload function: initWithSprites(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite) -- -- overload function: initWithSprites(cc.Sprite, cc.Sprite, cc.Sprite) -- -- @function [parent=#ControlSlider] initWithSprites -- @param self -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#ControlSlider] getMaximumValue -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ControlSlider] isTouchInside -- @param self -- @param #cc.Touch touch -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ControlSlider] getValue -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#ControlSlider] getThumbSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#ControlSlider] getProgressSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#ControlSlider] setBackgroundSprite -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#ControlSlider] setMaximumAllowedValue -- @param self -- @param #float float -------------------------------- -- overload function: create(cc.Sprite, cc.Sprite, cc.Sprite) -- -- overload function: create(char, char, char) -- -- overload function: create(char, char, char, char) -- -- overload function: create(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite) -- -- @function [parent=#ControlSlider] create -- @param self -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @return ControlSlider#ControlSlider ret (retunr value: cc.ControlSlider) -------------------------------- -- @function [parent=#ControlSlider] ControlSlider -- @param self return nil
mit
kitala1/darkstar
scripts/globals/items/walnut.lua
36
1072
----------------------------------------- -- ID: 5661 -- Item: Walnut -- Food Effect: 5Min, All Races ----------------------------------------- -- HP 30 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5661); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Olwyn.lua
30
1461
----------------------------------- -- Area: Bastok Markets -- NPC: Olwyn -- Standard Merchant NPC -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,OLWYN_SHOP_DIALOG); stock = { 0x1020, 445,1, --Ether 0x1037, 736,2, --Echo Drops 0x1010, 837,2, --Potion 0x1036, 2387,3, --Eye Drops 0x1034, 290,3 --Antidote } showNationShop(player, BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Cloister_of_Frost/Zone.lua
32
1658
----------------------------------- -- -- Zone: Cloister_of_Frost (203) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Frost/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(499.993,-1.696,523.343,194); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- 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
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Comittie.lua
38
1128
----------------------------------- -- Area: Port San d'Oria -- NPC: Comittie -- Type: Standard NPC -- @zone: 232 -- @pos -6.570 -9.8 -147.952 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
parsaalemi/parsa-antispam-bot
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) 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_namemod(msg, data, target) 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 local function lock_group_floodmod(msg, data, target) 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_floodmod(msg, data, target) 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 local function lock_group_membermod(msg, data, target) 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_membermod(msg, data, target) 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 local function unlock_group_photomod(msg, data, target) 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 show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end 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.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) 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 run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) 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] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
UB12/lionbot
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) 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_namemod(msg, data, target) 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 local function lock_group_floodmod(msg, data, target) 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_floodmod(msg, data, target) 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 local function lock_group_membermod(msg, data, target) 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_membermod(msg, data, target) 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 local function unlock_group_photomod(msg, data, target) 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 show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end 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.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) 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 run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) 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] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
kitala1/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/qm3.lua
19
1377
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: ??? Used for Norg quest "It's not your vault" -- @zone 176 -- @pos -173 26 252 2 ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Vault = player:getQuestStatus(OUTLANDS,ITS_NOT_YOUR_VAULT); if(Vault == QUEST_ACCEPTED and player:hasKeyItem(295) == false) then player:addKeyItem(295); player:messageSpecial(KEYITEM_OBTAINED,295); 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
speedata/publisher
src/lua/common/sd-callbacks.lua
1
3528
--- This is the location for file related callbacks. -- TeX uses the kpathsea library, which I disable right away (`texconfig.kpse_init=false` in sdini.lua). -- We still use the namespace kpse. -- -- sd-callbacks.lua -- speedata publisher -- -- For a list of authors see `git blame' -- See file COPYING in the root directory for license info. -- necessary callbacks if we want to use LuaTeX without kpathsea local trace_callbacks = false local function reader( asked_name ) if trace_callbacks then w("reader, asked_name = %q",tostring(asked_name)) end return { file = io.open(asked_name,"rb"), reader = function (t) local f = t.file return f:read('*l') end, close = function (t) t.file:close() end } end local rewrite_tbl = {} if os.getenv("SP_PATH_REWRITE") ~= nil then for _,v in ipairs(string.explode(os.getenv("SP_PATH_REWRITE"),",")) do a,b = table.unpack(string.explode(v,"=")) local str = string.gsub(a,"%-","%%-") str = string.gsub(str,"%(","%%(") str = string.gsub(str,"%)","%%)") rewrite_tbl[str]=b end end local function find_xxx_file( asked_name ) if trace_callbacks then w("find_xxx_file, asked_name = %q",tostring(asked_name)) end local file = kpse.find_file(asked_name) return file end local function return_asked_name( asked_name ) if trace_callbacks then w("return_asked_name, asked_name = %q",tostring(asked_name)) end return asked_name end local function read_font_file( name ) if trace_callbacks then w("read_font_file, name = %q",tostring(name)) end local f = io.open(name,"rb") local buf = f:read("*all") f:close() return true,buf,buf:len() end local function find_read_file( id_number,asked_name ) if trace_callbacks then w("find_read_file, id_number %q asked_name = %q",tostring(id_number), tostring(asked_name)) end local file = kpse.find_file(asked_name) return file end function find_write_file(id_number,asked_name) if trace_callbacks then w("find_write_file, id_number %q asked_name = %q",tostring(id_number), tostring(asked_name)) end return asked_name end local function read_xxx_file(name) if trace_callbacks then w("read_xxx_file, name = %q",tostring(name)) end return true,"",0 end callback.register("page_order_index",function(pagenum) local ppt = publisher.pagenum_tbl return ppt[pagenum] end) callback.register('open_read_file',reader) callback.register('find_opentype_file',return_asked_name) callback.register('find_type1_file', return_asked_name) callback.register('find_output_file', return_asked_name) callback.register('read_opentype_file',read_font_file) callback.register('read_type1_file', read_font_file) callback.register('find_write_file',find_write_file) callback.register('find_read_file',find_read_file) for _,t in ipairs({"find_font_file",'find_vf_file','find_format_file','find_map_file','find_enc_file','find_sfd_file','find_pk_file','find_data_file','find_image_file','find_truetype_file'}) do callback.register(t,find_xxx_file) end for _,t in ipairs({'read_vf_file','read_sdf_file','read_pk_file','read_data_file','read_font_file','read_map_file'}) do callback.register(t, read_xxx_file ) end function print_page_number() texio.write(string.format("> Shipout page %d\n",publisher.current_pagenumber)) end callback.register("start_page_number",print_page_number) callback.register("stop_page_number",false)
agpl-3.0
arekinath/loglunatic
loglunatic.lua
1
3588
#!/usr/bin/env luajit --[[ loglunatic -- logstash for lunatics Copyright (c) 2013, Alex Wilson, the University of Queensland Distributed under a BSD license -- see the LICENSE file in the root of the distribution. ]] local function usage() io.write("Usage: ./loglunatic.lua [-d|--daemon] [-p|--pidfile <file>] [-l|--logfile <file>] <config>\n") os.exit(1) end local fname = nil local lastarg = nil local logfile = "lunatic.log" local pidfile = "lunatic.pid" local foreground = true for i,v in ipairs(arg) do if v == "--daemon" or v == "-d" then foreground = false elseif lastarg == "--logfile" or lastarg == "-l" then logfile = v elseif lastarg == "--pidfile" or lastarg == "-p" then pidfile = v else fname = v end lastarg = v end if fname == nil then usage() end local f, err = loadfile(fname) if f == nil then io.write("Could not process config file " .. fname .. "\n") io.write(err .. "\n") os.exit(1) end local lpeg = assert(require('lpeg')) local ffi = assert(require('ffi')) local bit = assert(require('bit')) local l = assert(require('lunatic')) ffi.cdef[[ int fork(void); int setsid(void); int close(int); typedef void (*sig_t)(int); sig_t signal(int sig, sig_t func); int dup2(int from, int to); int open(const char *path, int oflag, ...); int fsync(int); ]] local O_WRONLY = 0x01 local O_APPEND = 0x08 local O_CREAT = 0x0200 if ffi.os == "Linux" then O_CREAT = 0x40 O_APPEND = 0x400 end if ffi.os == "POSIX" then O_CREAT = 0x100 end local function daemonize() assert(io.open(logfile, "w")) local r = ffi.C.fork() if r < 0 then print("fork failed: " .. ffi.errno) os.exit(1) elseif r > 0 then local pidfile = io.open(pidfile, "w") pidfile:write(r .. "\n") pidfile:close() os.exit(0) end ffi.C.setsid() local fd = ffi.C.open(logfile, bit.bor(O_WRONLY, O_APPEND)) local nullfd = ffi.C.open("/dev/null", bit.bor(O_WRONLY, O_APPEND)) assert(fd >= 0) assert(nullfd >= 0) assert(ffi.C.dup2(nullfd, 0) >= 0) assert(ffi.C.dup2(fd, 1) >= 0) assert(ffi.C.dup2(fd, 2) >= 0) ffi.C.fsync(fd) ffi.C.close(fd) ffi.C.close(nullfd) print("\ndaemonized ok, ready to go") ffi.C.fsync(1) end if not foreground then daemonize() end local rtor = l.Reactor.new() local env = {} env.string = string env.table = table env.math = math env.os = {} env.os.time = os.time env.os.date = os.date for k,v in pairs(lpeg) do env[k] = v end env.inputs = {} for k,v in pairs(l.inputs) do env.inputs[k] = function(tbl) tbl.reactor = rtor local chan = v(tbl) if tbl.restart then print("loglunatic: setting up restarter on input '" .. k .. "'") chan.old_close = chan.on_close chan.on_close = function(ch, rt) print("loglunatic: restarting closed input '" .. k .. "'") ch:old_close(rt) tbl.reactor = rt local newchan = v(tbl) newchan.old_close = newchan.on_close newchan.on_close = ch.on_close rt:add(newchan) local newinp = l.filters.input{ channel = newchan, reactor = rt } newchan.inp = newinp newinp.sink = ch.inp.sink end end rtor:add(chan) chan.inp = l.filters.input{ channel = chan, reactor = rtor } return chan.inp end end local reactorwrap = function(orig) return function(tbl) tbl.reactor = rtor return orig(tbl) end end local function wraptbl(dest, src) for k,v in pairs(src) do if type(v) == "table" then dest[k] = {} wraptbl(dest[k], v) else dest[k] = reactorwrap(v) end end end wraptbl(env, l.filters) env.outputs = {} wraptbl(env.outputs, l.outputs) env.link = l.link f = setfenv(f, env) f() print("starting reactor..") rtor:run()
bsd-3-clause
kitala1/darkstar
scripts/zones/Southern_San_dOria/npcs/Tek_Lengyon.lua
53
1848
----------------------------------- -- Area: Southern San d'Oria -- NPC: Tek Lengyon -- Type: Leathercraft Synthesis Image Support -- @pos -190.120 -2.999 2.770 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,7); local SkillCap = getCraftSkillCap(player, SKILL_LEATHERCRAFT); local SkillLevel = player:getSkillLevel(SKILL_LEATHERCRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY) == false) then player:startEvent(0x028C,SkillCap,SkillLevel,2,239,player:getGil(),0,0,0); else player:startEvent(0x028C,SkillCap,SkillLevel,2,239,player:getGil(),7075,0,0); end else player:startEvent(0x028C); -- Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x028C and option == 1) then player:messageSpecial(LEATHER_SUPPORT,0,5,2); player:addStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
crabman77/minetest-minetestforfun-server
mods/mobs/dog.lua
7
2157
-- Dog mobs:register_mob("mobs:dog", { -- animal, monster, npc, barbarian type = "npc", -- agressive, does 4 damage to player when hit passive = false, attacks_monsters = true, attack_type = "dogfight", damage = 2, -- 1 damage less than wolf -- health & armor hp_min = 15, hp_max = 20, armor = 200, -- textures and model collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4}, visual = "mesh", mesh = "mobs_wolf.x", drawtype = "front", textures = { {"mobs_dog.png"}, }, --visual_size = {x=1,y=1}, --Quel valeur lui mettre ? blood_texture = "mobs_blood.png", -- sounds makes_footstep_sound = true, sounds = { random = "mobs_wolf", war_cry = "mobs_wolf_attack", }, -- speed and jump walk_velocity = 2, run_velocity = 4, jump = true, stepheight = 1.2, step = 1.2, view_range = 16, drops = { {name = "mobs:meat_raw", chance = 1, min = 2, max = 3,}, }, -- damaged by water_damage = 0, lava_damage = 5, light_damage = 0, -- Special for pet owner = "", order = "follow", on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() local name = clicker:get_player_name() if not name then return end if item:get_name() == "mobs:meat_raw" then local hp = self.object:get_hp() -- return if full health if hp >= self.hp_max then minetest.chat_send_player(name, "Dog at full health.") return end hp = hp + 4 -- add restorative value -- new health shouldn't exceed self.hp_max if hp > self.hp_max then hp = self.hp_max end self.object:set_hp(hp) -- Take item if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end else if self.owner == "" then self.owner = clicker:get_player_name() else if self.order == "follow" then self.order = "stand" else self.order = "follow" end end end end, -- model animation animation = { stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, speed_normal = 15, speed_run = 15, }, }) mobs:register_egg("mobs:dog", "Dog", "mobs_dog_inv.png", 1)
unlicense
Pulse-Eight/drivers
Control4/sky_hd_ip_pulse-eight/common/c4_notify.lua
9
1689
--[[============================================================================= Notification Functions Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.p8declares" --[[============================================================================= SendNotify(notifyText, tParams, bindingID) Description Forwards a notification to the proxy with a list of parameters Parameters notifyText(string) - The function identifier for the proxy tParams(table) - Table of key value pairs that hold the the parameters and their values used in the proxy function bindingID(int) - The requests binding id Returns Nothing ===============================================================================]] function SendNotify(notifyText, tParams, bindingID) C4:SendToProxy(bindingID, notifyText, tParams, "NOTIFY") end --[[============================================================================= SendSimpleNotify(notifyText, ...) Description Forwards a notification to the proxy with no parameters Parameters notifyText(string) - The function identifier for the proxy bindingID(int) - Optional parameter containing the requests binding id, if not specified then the DEFAULT_PROXY_ID is given. Returns Nothing ===============================================================================]] function SendSimpleNotify(notifyText, ...) bindingID = select(1, ...) or DEFAULT_PROXY_BINDINGID C4:SendToProxy(bindingID, notifyText, {}, "NOTIFY") end
apache-2.0
Pulse-Eight/drivers
Control4/sky_q_ip_pulse-eight/common/c4_notify.lua
9
1689
--[[============================================================================= Notification Functions Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.p8declares" --[[============================================================================= SendNotify(notifyText, tParams, bindingID) Description Forwards a notification to the proxy with a list of parameters Parameters notifyText(string) - The function identifier for the proxy tParams(table) - Table of key value pairs that hold the the parameters and their values used in the proxy function bindingID(int) - The requests binding id Returns Nothing ===============================================================================]] function SendNotify(notifyText, tParams, bindingID) C4:SendToProxy(bindingID, notifyText, tParams, "NOTIFY") end --[[============================================================================= SendSimpleNotify(notifyText, ...) Description Forwards a notification to the proxy with no parameters Parameters notifyText(string) - The function identifier for the proxy bindingID(int) - Optional parameter containing the requests binding id, if not specified then the DEFAULT_PROXY_ID is given. Returns Nothing ===============================================================================]] function SendSimpleNotify(notifyText, ...) bindingID = select(1, ...) or DEFAULT_PROXY_BINDINGID C4:SendToProxy(bindingID, notifyText, {}, "NOTIFY") end
apache-2.0
Teaonly/easyLearning.js
simple_lstm/train.lua
2
4831
require 'torch' require 'nn' require 'nngraph' require 'optim' require 'lfs' local toy_data = require 'toy_data' local model_utils = require 'model_utils' local LSTM = require 'LSTM' local INPUT_SIZE = 4 local OUTPUT_SIZE = 15 local RNN_SIZE = 196 local LAYER_NUMBER = 2 local BATCH_SIZE = 16 local MAX_TIMING_STEP = 128 local GRAD_CLIP = 5.0 toyRNN = {}; toyRNN.model = LSTM.lstm(INPUT_SIZE, OUTPUT_SIZE, RNN_SIZE, LAYER_NUMBER) toyRNN.criterion = nn.ClassNLLCriterion() -- global var for training params, grad_params = model_utils.combine_all_parameters(toyRNN.model) -- init weights with simple uniform random params:uniform(-0.08, 0.08) -- initialize the LSTM forget gates with slightly higher biases to encourage remembering in the beginning for layer_idx = 1, LAYER_NUMBER do for _,node in ipairs(toyRNN.model.forwardnodes) do if node.data.annotations.name == "i2h_" .. layer_idx then print('setting forget gate biases to 1 in LSTM layer ' .. layer_idx) -- the gates are, in order, i,f,o,g, so f is the 2nd block of weights node.data.module.bias[{{RNN_SIZE+1, 2*RNN_SIZE}}]:fill(1.0) end end end toyRNN.clone_models = model_utils.clone_many_times(toyRNN.model, MAX_TIMING_STEP) toyRNN.clone_criterions = model_utils.clone_many_times(toyRNN.criterion, MAX_TIMING_STEP) -- init internal state cell_data = {} for i = 1, LAYER_NUMBER*2 do cell_data[i] = torch.ones(BATCH_SIZE, RNN_SIZE) * 0.05 end -- training function local feval = function(x) if ( x ~= params ) then params:copy(x) end grad_params:zero() ------------------ get minibatch ------------------- local step_number = (torch.random() % (MAX_TIMING_STEP - 64)) + 64 --local step_number = MAX_TIMING_STEP local x, y = toy_data.get_batch(BATCH_SIZE, step_number) ------------------- forward pass ------------------- local predictions = {} -- softmax outputs local loss = 0 local rnn_state = {}; rnn_state[0] = {unpack(cell_data)} for t=1, step_number do toyRNN.clone_models[t]:training() local lst = toyRNN.clone_models[t]:forward{x[t], unpack(rnn_state[t-1])} rnn_state[t] = {} for i=1, #lst - 1 do table.insert(rnn_state[t], lst[i]) end -- extract the state, without output predictions[t] = lst[#lst] -- last element is the prediction loss = loss + toyRNN.clone_criterions[t]:forward(predictions[t], y[t]) end loss = loss / step_number ------------------ backward pass ------------------- local drnn_state = {[step_number] = {}}; -- there is no loss on state at last step for i = 1, LAYER_NUMBER*2 do drnn_state[step_number][i] = torch.zeros(BATCH_SIZE, RNN_SIZE) end for t=step_number, 1, -1 do -- backprop through loss, and softmax/linear local doutput_t = toyRNN.clone_criterions[t]:backward(predictions[t], y[t]) table.insert(drnn_state[t], doutput_t) local dlst = toyRNN.clone_models[t]:backward({x[t], unpack(rnn_state[t-1])}, drnn_state[t]) drnn_state[t-1] = {} for k,v in pairs(dlst) do if k > 1 then -- k == 1 is gradient on x, which we dont need -- note we do k-1 because first item is dembeddings, and then follow the· -- derivatives of the state, starting at index 2. I know... drnn_state[t-1][k-1] = v end end end grad_params:clamp(-GRAD_CLIP, GRAD_CLIP) return loss, grad_params end local doTest = function() toyRNN.model:evaluate(); local step_number = MAX_TIMING_STEP local xx, yy = toy_data.singleSequence(step_number) local x = torch.Tensor(1, 4) local rnn_state = {} for i = 1, LAYER_NUMBER*2 do rnn_state[i] = torch.ones(1, RNN_SIZE) * 0.05 end local score = 0 for t=1, step_number do -- one hot input x[1]:zero() x[1][xx[t]+1] = 1 local lst = toyRNN.model:forward({x, unpack(rnn_state)}) for i = 1, #rnn_state do rnn_state[i] = lst[i] end local _, prediction = lst[#lst]:max(2) if ( prediction[1][1] == yy[t] ) then score = score + 1 end end return score end local doTrain = function(num) train_loss = {} local optim_state = {learningRate = 0.02, alpha = 0.95} local maxScore = 0 for i = 1, num do local _, loss = optim.rmsprop(feval, params, optim_state) print('>>>Iterating ' .. i .. ' with loss = ' .. loss[1]) if ( i % 500 == 0) then optim_state.learningRate = optim_state.learningRate * 0.99 end if ( i % 100 == 0) then local totalScore = 0 for j = 1, 32 do totalScore = totalScore + doTest() end if ( totalScore > maxScore ) then torch.save("./model.bin", toyRNN.model); maxScore = totalScore end print(">>>>>>>>>>>>>>" .. maxScore/(32*MAX_TIMING_STEP) .. " " .. totalScore / (32*MAX_TIMING_STEP)); end end end doTrain(50000)
mit
kaustavha/rackspace-monitoring-agent
hostinfo/fail2ban.lua
3
6014
--[[ Copyright 2015 Rackspace 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 HostInfo = require('./base').HostInfo local Transform = require('stream').Transform local misc = require('./misc') local async = require('async') local Reader = Transform:extend() function Reader:initialize() Transform.initialize(self, {objectMode = true}) self._pushed = false end local LogfilePathReader = Reader:extend() function LogfilePathReader:_transform(line, cb) if not line:find('Current logging target is:') then -- e.g. '- /var/log/fail2ban.log' -> /var/log/fail2ban.log self:push(line:match('%s(.+)')) end cb() end local JailsListReader = Reader:extend() function JailsListReader:_transform(line, cb) if line:find('%sJail%slist:') then local csvJailsList = line:match('%\t(.+)') or '' local jails = {} csvJailsList:gsub('(%a+)%p-%s-', function(c) table.insert(jails, c) end) self:push(jails) end cb() end local ActivityLogReader = Reader:extend() function ActivityLogReader:_transform(line, cb) if line:find('%sBan') or line:find('%sUnban') then self:push(line) end cb() end local BannedStatsReader = Reader:extend() function BannedStatsReader:_transform(line, cb) local dataTable = {} line:gsub("%S+", function(c) table.insert(dataTable, c) end) self:push({ ip = dataTable[#dataTable], status = dataTable[#dataTable - 1], jail = dataTable[#dataTable - 2]:match('%[(.*)%]') }) cb() end --[[ Are autoupdates enabled? ]]-- local Info = HostInfo:extend() function Info:initialize() HostInfo.initialize(self) end function Info:_run(callback) local function getLogfilePath(cb) local errTable = {} local child = misc.run('fail2ban-client', {'get', 'logtarget'}) local loglocation local reader = LogfilePathReader:new() child:pipe(reader) reader:on('error', function(err) misc.safeMerge(errTable, err) end) reader:on('data', function(data) loglocation = data end) reader:once('end', function() local alternateLoglocation = '/var/log/messages' if loglocation == 'SYSLOG' then local readStream = misc.read(loglocation) readStream:on('error', function(err) misc.safeMerge(errTable, err) readStream:close() cb({loglocation = '/var/log/syslog'}, errTable) end) readStream:on('data', function(line) readStream:close() cb({loglocation = alternateLoglocation}, errTable) end) else cb({loglocation = loglocation}, errTable) end end) end local function getActivityLogAndBannedStats(logfilePath, cb) local errTable, outTable = {}, {} outTable.banned, outTable.activity = {}, {} local counter = 500 -- lets limit this at 500 local readStream = misc.read(logfilePath) local reader = ActivityLogReader:new() local bannedStatsReader = BannedStatsReader:new() -- Catch no file found errors readStream:on('error', function(err) table.insert(errTable, err) return cb(nil, errTable) end) readStream:pipe(reader) reader:on('data', function(data) if counter ~= 0 then counter = counter - 1 table.insert(outTable.activity, data) bannedStatsReader:write(data) end end) reader:on('error', function(err) misc.safeMerge(errTable, err) end) reader:once('end', function() bannedStatsReader:emit('end') end) bannedStatsReader:on('data', function(data) local ban if outTable.banned[data.ip] then if outTable.banned[data.ip][data.jail] then ban = outTable.banned[data.ip][data.jail] end else ban = {count = 0, status = 'None' } end if data.status == 'Ban' then ban.count = ban.count + 1 end ban.status = data.status outTable.banned[data.ip] = {} outTable.banned[data.ip][data.jail] = ban end) bannedStatsReader:on('error', function(err) misc.safeMerge(errTable, err) end) bannedStatsReader:once('end', function() cb(outTable, errTable) end) end local function getJailsList(cb) local errTable, outTable = {}, {} local child = misc.run('fail2ban-client', {'status'}) local reader = JailsListReader:new() child:pipe(reader) reader:on('error', function(err) table.insert(errTable, err) end) reader:on('data', function(data) outTable.jails = data end) reader:once('end', function() cb(outTable, errTable) end) end local errTable, outTable = {}, {} local function finalCb() self:_pushParams(errTable, outTable) callback() end async.parallel({ function(cb) getLogfilePath(function(out, err) misc.safeMerge(errTable, err) -- err here should be just {} if out.loglocation then getActivityLogAndBannedStats(out.loglocation, function(out, err) misc.safeMerge(outTable, out) misc.safeMerge(errTable, err) cb() end) else cb() end end) end, function(cb) getJailsList(function(out, err) misc.safeMerge(outTable, out) misc.safeMerge(errTable, err) cb() end) end }, finalCb) end function Info:getPlatforms() return {'linux'} end function Info:getType() return 'FAIL2BAN' end exports.Info = Info exports.LogfilePathReader = LogfilePathReader exports.JailsListReader = JailsListReader exports.ActivityLogReader = ActivityLogReader exports.BannedStatsReader = BannedStatsReader
apache-2.0
ioiasff/DSA
plugins/anti_spam.lua
417
3978
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds local data = load_data(_config.moderation.data) -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end if msg.from.username then redis:hset(hash, 'username', msg.from.username) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is one or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id -- Ignore mods,owner and admins if is_momod(msg) then return msg end local chat = msg.to.id local user = msg.from.id -- Return end if user was kicked before if kicktable[user] == true then return end kick_user(user, chat) if msg.to.type == "user" then block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end local name = user_print_name(msg.from) --save it to log file savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ") -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) local username = " " if msg.from.username ~= nil then username = msg.from.username end local name = user_print_name(msg.from) --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)") local log_group = 1 --set log group caht id --send it to log group send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)") end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
rezaph/Nano-bot
plugins/anti_spam.lua
417
3978
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds local data = load_data(_config.moderation.data) -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end if msg.from.username then redis:hset(hash, 'username', msg.from.username) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is one or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id -- Ignore mods,owner and admins if is_momod(msg) then return msg end local chat = msg.to.id local user = msg.from.id -- Return end if user was kicked before if kicktable[user] == true then return end kick_user(user, chat) if msg.to.type == "user" then block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end local name = user_print_name(msg.from) --save it to log file savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ") -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) local username = " " if msg.from.username ~= nil then username = msg.from.username end local name = user_print_name(msg.from) --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)") local log_group = 1 --set log group caht id --send it to log group send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)") end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
mahdi1062/avira
plugins/anti_spam.lua
10
5319
kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "یوزر ["..msg.from.id.."] به دلیل اسپم بلاک شد") savelog(msg.from.id.." PM", "یوزر ["..msg.from.id.."] به دلیل اسپم بلاک شد") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "یوزر @"..username.."["..msg.from.id.."] به دلیل اسپم از گروه اخراج شد") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "یوزر "..name_log.."["..msg.from.id.."] به دلیل اسپم از گروه اخراج شد") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "یوزر [ "..name.." ]"..msg.from.id.." به دلیل اسپم بن گلوبالی شد") send_large_msg("channel#id"..msg.to.id, "یوزر [ "..name.." ]"..msg.from.id.." به دلیل اسپم بن گلوبالی شد") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "یوزر [ "..name.." ] ( @"..username.." )"..msg.from.id.." از ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] به دلیل اسپم بن گلوبالی شد" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
kitala1/darkstar
scripts/zones/VeLugannon_Palace/npcs/Treasure_Coffer.lua
16
3526
----------------------------------- -- Area: Ve'Lugannon Palace -- NPC: Treasure Coffer -- @zone 177 ----------------------------------- package.loaded["scripts/zones/VeLugannon_Palace/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/VeLugannon_Palace/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1060,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1060,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: Map ----------- if(player:hasKeyItem(MAP_OF_THE_VELUGANNON_PALACE) == false) then questItemNeeded = 3; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if(questItemNeeded == 3) then player:addKeyItem(MAP_OF_THE_VELUGANNON_PALACE); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_VELUGANNON_PALACE); -- Map of the Ve'Lugannon Palace (KI) elseif(questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if(mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1060); 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
apletnev/koreader
frontend/ui/widget/buttonprogresswidget.lua
2
2816
local Blitbuffer = require("ffi/blitbuffer") local Button = require("ui/widget/button") local Device = require("device") local Geom = require("ui/geometry") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local FrameContainer = require("ui/widget/container/framecontainer") local Size = require("ui/size") local UIManager = require("ui/uimanager") local _ = require("gettext") local Screen = Device.screen local ButtonProgressWidget = InputContainer:new{ width = Screen:scaleBySize(216), height = Size.item.height_default, font_face = "cfont", font_size = 16, enabled = true, num_buttons = 2, position = 1, } function ButtonProgressWidget:init() self.buttonprogress_frame = FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, color = Blitbuffer.COLOR_GREY, radius = Size.radius.window, bordersize = 0, padding = Size.padding.small, dim = not self.enabled, width = self.width, height = self.height, } self.buttonprogress_content = HorizontalGroup:new{} self:update() self.buttonprogress_frame[1] = self.buttonprogress_content self[1] = self.buttonprogress_frame self.dimen = Geom:new(self.buttonprogress_frame:getSize()) end function ButtonProgressWidget:update() self.buttonprogress_content:clear() local button_margin = Size.margin.tiny local button_padding = Size.padding.button local button_bordersize = Size.border.button local preselect local button_width = math.floor(self.width / self.num_buttons) - 2*button_padding - 2*button_margin - 2*button_bordersize for i = 1, self.num_buttons do if self.position >= i then preselect = true else preselect = false end local button = Button:new{ text = "", radius = 0, margin = button_margin, padding = button_padding, bordersize = button_bordersize, enabled = true, width = button_width, preselect = preselect, text_font_face = self.font_face, text_font_size = self.font_size, callback = function() self.callback(i) self.position = i self:update() end, hold_callback = function() self.hold_callback(i) end, } table.insert(self.buttonprogress_content, button) end UIManager:setDirty(self.show_parrent, function() return "ui", self.dimen end) UIManager:setDirty("all") end function ButtonProgressWidget:setPosition(position) self.position = position self:update() end return ButtonProgressWidget
agpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Solgierte.lua
36
1375
----------------------------------- -- Area: Port San d'Oria -- NPC: Solgierte -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x237); 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
kitala1/darkstar
scripts/zones/PsoXja/npcs/_09d.lua
8
1608
----------------------------------- -- Area: Pso'Xja -- NPC: _09d (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos -330.000 14.074 -261.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local X=player:getXPos(); if (npc:getAnimation() == 9) then if(X <= 301)then if(GetMobAction(16814094) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED); SpawnMob(16814094,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif(X >= 302)then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if(csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Zeruhn_Mines/Zone.lua
30
2566
----------------------------------- -- -- Zone: Zeruhn_Mines (172) -- ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/zone"); require("scripts/zones/Zeruhn_Mines/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17481844}; SetGroundsTome(tomes); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (prevZone == 143) then cs = 0x0096; if (player:getQuestStatus(BASTOK, BLADE_OF_DARKNESS) == QUEST_ACCEPTED) then if (player:getVar("ZeruhnMines_Zeid_CS") == 0) then cs = 0x0082; elseif (player:hasItem(16607) == false) then cs = 0x0083; end elseif (player:getQuestStatus(BASTOK,BLADE_OF_DEATH) == QUEST_ACCEPTED) then if (player:hasItem(16607) == false) then cs = 0x0083; end end elseif ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-270.707,14.159,-20.268,0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- 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 == 0x0082 or csid == 0x0083) then if (player:getFreeSlotsCount() > 0) then player:addItem(16607); player:setVar("ChaosbringerKills", 0); player:messageSpecial(ITEM_OBTAINED,16607); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16607); end player:setVar("ZeruhnMines_Zeid_CS", 1); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Beaucedine_Glacier/npcs/relic.lua
38
1859
----------------------------------- -- Area: Beaucedine Glacier -- NPC: <this space intentionally left blank> -- @pos -89 0 -374 111 ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beaucedine_Glacier/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18281 and trade:getItemCount() == 4 and trade:hasItemQty(18281,1) and trade:hasItemQty(1574,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then player:startEvent(139,18282); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 139) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18282); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453); else player:tradeComplete(); player:addItem(18282); player:addItem(1453,30); player:messageSpecial(ITEM_OBTAINED,18282); player:messageSpecial(ITEMS_OBTAINED,1453,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/TextIDs.lua
5
4857
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED_1 = 6414; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>.<<<Prompt>>> ITEM_CANNOT_BE_OBTAINED_2 = 6415; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. Come back after sorting your inventory. ITEM_CANNOT_BE_OBTAINED_3 = 6416; -- You cannot obtain the item. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6417; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6418; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. GIL_OBTAINED = 6419; -- Obtained <<<Numeric Parameter 0>>> gil. KEYITEM_OBTAINED = 6421; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>3<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. HOMEPOINT_SET = 24; -- Home point set! FISHING_MESSAGE_OFFSET = 7201; -- You can't fish here. ITEM_DELIVERY_DIALOG = 7916; -- Now delivering parcels to rooms everywhere! -- Dialogs FLYER_REFUSED = 7528; -- This person isn't interested. FLYER_ALREADY = 7529; -- This person already has a flyer. FLYER_ACCEPTED = 7530; -- Your flyer is accepted! FLYERS_HANDED = 7531; -- You've handed outflyer(s). PORTAURE_DIALOG = 7793; -- What's this? A magic shop? Hmm...I could use a new line of work, and magic just might be the ticket! ANSWALD_DIALOG = 7813; -- A magic shop? Oh, it's right near here. I'll go check it out sometime. PRIETTA_DIALOG = 7837; -- This is the first I've heard of a magic shop here in San d'Oria. Such arts have never been popular in the Kingdom. AUVARE_DIALOG = 7844; -- What have I got here? Look, I can't read, but I takes what I gets, and you ain't getting it back! MIENE_DIALOG = 7897; -- Oh, a magic shop... Here in San d'Oria? I'd take a look if I got more allowance. ANSWALD_MESSAGE = 8390; -- Answald looks over curiously for a moment. PRIETTA_MESSAGE = 8391; -- Prietta looks over curiously for a moment. MIENE_MESSAGE = 8392; -- Miene looks over curiously for a moment. PORTAURE_MESSAGE = 8393; -- Portaure looks over curiously for a moment. AUVARE_MESSAGE = 8394; -- Auvare looks over curiously for a moment. -- Shop Texts ALBINIE_SHOP_DIALOG = 7857; -- Welcome to my simple shop. COULLAVE_SHOP_DIALOG = 7903; -- Can I help you? CROUMANGUE_SHOP_DIALOG = 7904; -- Can't fight on an empty stomach. How about some nourishment? VENDAVOQ_OPEN_DIALOG = 7911; -- Vandoolin! Vendavoq vring voods vack vrom Vovalpolos! Vuy! Vuy! VENDAVOQ_CLOSED_DIALOG = 7912; -- Vandoolin... Vendavoq's vream vo vell voods vrom vometown vf Vovalpolos... FIVA_OPEN_DIALOG = 7905; -- I've got imports from Kolshushu! MILVA_OPEN_DIALOG = 7906; -- How about some produce from Sarutabaruta? FIVA_CLOSED_DIALOG = 7907; -- I'm trying to sell goods from Kolshushu. But I can't because we don't have enough influence there. MILVA_CLOSED_DIALOG = 7908; -- I want to import produce from Sarutabaruta... But I can't do anything until we control that region! NIMIA_CLOSED_DIALOG = 7909; -- I can't sell goods from the lowlands of Elshimo because it's under foreign control. PATOLLE_CLOSED_DIALOG = 7910; -- I'm trying to find goods from Kuzotz. But how can I when it's under foreign control? DEGUERENDARS_OPEN_DIALOG = 7913; -- Welcome! Have a look at these rare goods from Tavnazia! DEGUERENDARS_CLOSED_DIALOG = 7914; -- With that other nation in control of the region, there is no way for me to import goods from Tavnazia... DEGUERENDARS_COP_NOT_COMPLETED = 7915; -- Why must I wait for the Kingdom to issue a permit allowing me to set up shop? How am I to feed my children in the meantime!? BONMAURIEUT_CLOSED_DIALOG = 8250; -- I would like to sell goods from the Elshimo Uplands, but I cannot, as it's under foreign control. NIMIA_OPEN_DIALOG = 8251; -- Hello, friend! Can I interest you in specialty goods from the Elshimo Lowlands? PATOLLE_OPEN_DIALOG = 8252; -- How about some specialty goods from Kuzotz? BONMAURIEUT_OPEN_DIALOG = 8253; -- My shipment is in! Would you like to see what has just arrived from the Elshimo Uplands? -- conquest Base CONQUEST_BASE = 7042; -- Tallying conquest results...
gpl-3.0
d-o/LUA-LIB
src/rinLibrary/K400Axle.lua
2
1416
------------------------------------------------------------------------------- --- Axle scle functions. -- Functions to support the K422 Axle Weigher -- @module rinLibrary.Device.Axle -- @author Pauli -- @copyright 2014 Rinstrum Pty Ltd ------------------------------------------------------------------------------- local naming = require 'rinLibrary.namings' return function (_M, private, deprecated) local REG_DYNAMIC_MODE = 0xA708 private.registerDeviceInitialiser(function() private.addRegisters{ dynamic_scale = private.k422(0xA713), axle_timeout = private.k422(0xA705) } end) --- Axle Modes. --@table axleModes -- @field dynamic Dynamic axle detection -- @field off No axle detection -- @field static Static axle detection local axleModeOptions = { dynamic = 0, static = 1, off = 2 } ------------------------------------------------------------------------------- -- Function to change the axle detection mode -- @function setAxleMode -- @tparam axleModes Axle mode to change to -- @usage -- device.setAxleMode('off') -- device.selectOption(...) -- device.setAxleMode('dynamic') private.registerDeviceInitialiser(function() private.exposeFunction('setAxleMode', private.k422(true), function(mode) local s = naming.convertNameToValue(mode, axleModeOptions, 0, 0, 2) private.writeReg(REG_DYNAMIC_MODE, s) end) end) end
gpl-3.0
crabman77/minetest-minetestforfun-server
mods/more_chests/dropbox.lua
8
2558
local function has_locked_chest_privilege(meta, player) if player:get_player_name() ~= meta:get_string("owner") then return false end return true end minetest.register_node("more_chests:dropbox", { description = "Dropbox", tiles = {"default_chest_top.png", "default_chest_top.png", "dropbox_right.png", "default_chest_side.png", "default_chest_side.png", "dropbox_front.png"}, paramtype2 = "facedir", groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2}, legacy_facedir_simple = true, sounds = default.node_sound_wood_defaults(), after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", "Dropbox (owned by ".. meta:get_string("owner")..")") end, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", "size[8,9]".. "list[current_name;main;0,0;8,4;]".. "list[current_player;main;0,5;8,4;]".. "listring[current_name;main]" .. "listring[current_player;main]") meta:set_string("infotext", "Chest") local inv = meta:get_inventory() inv:set_size("main", 8*4) end, can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if not has_locked_chest_privilege(meta, player) then minetest.log("action", player:get_player_name().. " tried to access a dropbox belonging to ".. meta:get_string("owner").." at ".. minetest.pos_to_string(pos)) return 0 end return stack:get_count() end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().. " moves stuff in dropbox at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " moves stuff to dropbox at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " takes stuff from dropbox at "..minetest.pos_to_string(pos)) end, }) minetest.register_craft({ output = 'more_chests:dropbox', recipe = { {'default:wood','','default:wood'}, {'default:wood','default:steel_ingot','default:wood'}, {'default:wood','default:wood','default:wood'} } })
unlicense
minetest-australopithecus/minetest-australopithecus-utils
test/arrayutil.lua
2
4330
-- Load the test file. dofile("./mods/utils/test.lua") -- Load the file for testing. dofile("./mods/utils/arrayutil.lua") dofile("./mods/utils/list.lua") dofile("./mods/utils/mathutil.lua") dofile("./mods/utils/tableutil.lua") test.start("arrayutil") test.run("contains", function() test.equals(false, arrayutil.contains({}, nil)) test.equals(true, arrayutil.contains({ "test" }, "test")) test.equals(true, arrayutil.contains({ "a", "b", "test" }, "test")) test.equals(true, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, "test")) test.equals(true, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "a", "b", "c" })) test.equals(true, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "b", "c" })) test.equals(true, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "d", "e" })) test.equals(true, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "d", "e", "a", "b" })) test.equals(false, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "b", "d" })) test.equals(false, arrayutil.contains({ "a", "b" , "c", "test", "d", "e" }, { "d", "e", "a", "c" })) end) test.run("create2d", function() local array = arrayutil.create2d(1, 1, 4, 3, "value") test.equals("value", array[1][1]) test.equals("value", array[1][3]) test.equals("value", array[4][1]) test.equals("value", array[4][3]) test.equals(nil, array[0]) test.equals(nil, array[1][0]) test.equals(nil, array[5]) test.equals(nil, array[4][4]) end) test.run("create3d", function() local array = arrayutil.create3d(1, 1, 1, 4, 3, 2, "value") test.equals("value", array[1][1][1]) test.equals("value", array[1][1][2]) test.equals("value", array[4][1][1]) test.equals("value", array[4][3][2]) test.equals(nil, array[0]) test.equals(nil, array[1][0]) test.equals(nil, array[5]) test.equals(nil, array[4][3][3]) end) test.run("index", function() test.equals(-1, arrayutil.index({}, nil)) test.equals(1, arrayutil.index({ "test" }, "test")) test.equals(3, arrayutil.index({ "a", "b", "test" }, "test")) test.equals(4, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, "test")) test.equals(1, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "a", "b", "c" })) test.equals(2, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "b", "c" })) test.equals(5, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "d", "e" })) test.equals(5, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "d", "e", "a", "b" })) test.equals(-1, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "b", "d" })) test.equals(-1, arrayutil.index({ "a", "b" , "c", "test", "d", "e" }, { "d", "e", "a", "c" })) end) test.run("next_matching_column", function() local array = { { "", "", "", "", "" }, { "", "something", "", "", "" }, { "", "", "", "", "" }, { "", "", "", "something", "" }, { "", "", "", "", "" } } test.equals(2, arrayutil.next_matching_column(array)) test.equals(4, arrayutil.next_matching_column(array, 3)) test.equals(-1, arrayutil.next_matching_column(array, 5)) -- Reverse test.equals(4, arrayutil.previous_matching_column(array)) test.equals(2, arrayutil.previous_matching_column(array, 3)) test.equals(-1, arrayutil.previous_matching_column(array, 1)) end) test.run("next_matching_row", function() local array = { { "", "", "", "", "" }, { "", "", "something", "", "" }, { "", "", "", "", "" }, { "", "", "", "something", "" }, { "", "", "", "", "" } } test.equals(2, arrayutil.next_matching_row(array)) test.equals(4, arrayutil.next_matching_row(array, 3)) test.equals(-1, arrayutil.next_matching_row(array, 5)) -- Reverse test.equals(4, arrayutil.previous_matching_row(array)) test.equals(2, arrayutil.previous_matching_row(array, 3)) test.equals(-1, arrayutil.previous_matching_row(array, 1)) end) test.run("reduce2d", function() local reduced = arrayutil.reduce2d({}) local expected = {} test.equals(true, tableutil.equals(reduced, expected)) reduced = arrayutil.reduce2d({ { "", "", "", "", "" }, { "", "", "something", "", "" }, { "", "", "", "", "" }, { "", "", "", "something", "" }, { "", "", "", "", "" } }) expected = arrayutil.reduce2d({ { "something", "" }, { "", "" }, { "", "something" }, }) test.equals(true, tableutil.equals(reduced, expected)) end)
bsd-2-clause
nicodinh/cuberite
MCServer/Plugins/APIDump/Hooks/OnPlayerRightClick.lua
36
1957
return { HOOK_PLAYER_RIGHT_CLICK = { CalledWhen = "A right-click packet is received from the client. Plugin may override / refuse.", DefaultFnName = "OnPlayerRightClick", -- also used as pagename Desc = [[ This hook is called when Cuberite receives a right-click packet from the {{cClientHandle|client}}. It is called before any processing whatsoever is performed on the packet, meaning that hacked / malicious clients may be trigerring this event very often and with unchecked parameters. Therefore plugin authors are advised to use extreme caution with this callback.</p> <p> Plugins may refuse the default processing for the packet, causing Cuberite to behave as if the packet has never arrived. This may, however, create inconsistencies in the client - the client may think that they placed a block, while the server didn't process the placing, etc. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose client sent the packet" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" }, { Name = "CursorX", Type = "number", Notes = "X-coord of the mouse crosshair on the block" }, { Name = "CursorY", Type = "number", Notes = "Y-coord of the mouse crosshair on the block" }, { Name = "CursorZ", Type = "number", Notes = "Z-coord of the mouse crosshair on the block" }, }, Returns = [[ If the function returns false or no value, Cuberite calls other plugins' callbacks and finally sends the packet for further processing.</p> <p> If the function returns true, no other plugins are called, processing is halted. ]], }, -- HOOK_PLAYER_RIGHT_CLICK }
apache-2.0
kitala1/darkstar
scripts/zones/Yughott_Grotto/npcs/Mining_Point.lua
29
1099
----------------------------------- -- Area: Yughott Grotto -- NPC: Mining Point ----------------------------------- package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil; ------------------------------------- require("scripts/globals/mining"); require("scripts/zones/Yughott_Grotto/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startMining(player,player:getZoneID(),npc,trade,0x0064); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
JacobFischer/Joueur.lua
games/newtonian/machine.lua
2
2835
-- Machine: A machine in the game. Used to refine ore. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.newtonian.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A machine in the game. Used to refine ore. -- @classmod Machine local Machine = class(GameObject) -- initializes a Machine with basic logic as provided by the Creer code generator function Machine:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- What type of ore the machine takes it. Also determines the type of material it outputs. (redium or blueium). self.oreType = "" --- The amount of ore that needs to be inputted into the machine for it to be worked. self.refineInput = 0 --- The amount of refined ore that is returned after the machine has been fully worked. self.refineOutput = 0 --- The number of times this machine needs to be worked to refine ore. self.refineTime = 0 --- The Tile this Machine is on. self.tile = nil --- Tracks how many times this machine has been worked. (0 to refineTime). self.worked = 0 --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Machine:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Machine
mit
JacobFischer/Joueur.lua
games/stumped/ai.lua
2
5211
-- This is where you build your AI for the Stumped game. local class = require("joueur.utilities.class") local BaseAI = require("joueur.baseAI") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- the AI functions for the Stumped game. -- @classmod AI local AI = class(BaseAI) --- The reference to the Game instance this AI is playing. -- @field[Game] self.game -- @see Game --- The reference to the Player this AI controls in the Game. -- @field[Player] self.player -- @see Player --- this is the name you send to the server to play as. function AI:getName() -- <<-- Creer-Merge: get-name -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. return "Stumped Lua Player" -- REPLACE THIS WITH YOUR TEAM NAME! -- <<-- /Creer-Merge: get-name -->> end --- this is called once the game starts and your AI knows its playerID and game. You can initialize your AI here. function AI:start() -- <<-- Creer-Merge: start -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your start logic -- <<-- /Creer-Merge: start -->> end --- this is called when the game's state updates, so if you are tracking anything you can update it here. function AI:gameUpdated() -- <<-- Creer-Merge: game-updated -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your game updated logic -- <<-- /Creer-Merge: game-updated -->> end --- this is called when the game ends, you can clean up your data and dump files here if need be -- @tparam boolean won true means you won, won == false means you lost -- @tparam string reason why you won or lost function AI:ended(won, reason) -- <<-- Creer-Merge: ended -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your ended -- <<-- /Creer-Merge: ended -->> end -- Game Logic Functions: functions you must fill out to send data to the game server to actually play the game! -- --- This is called every time it is this AI.player's turn. -- @treturn bool Represents if you want to end your turn. True means end your turn, False means to keep your turn going and re-call this function. function AI:runTurn() -- <<-- Creer-Merge: runTurn -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- Put your game logic here for runTurn return true -- <<-- /Creer-Merge: runTurn -->> end --- A very basic path finding algorithm (Breadth First Search) that when given a starting Tile, will return a valid path to the goal Tile. -- @tparam Tile start the starting Tile -- @tparam Tile goal the goal Tile -- @treturns Table(Tile) An array of Tiles representing the path, the the first element being a valid adjacent Tile to the start, and the last element being the goal. function AI:findPath(start, goal) if start == goal then -- no need to make a path to here... return Table() end -- queue of the tiles that will have their neighbors searched for 'goal' local fringe = Table() -- How we got to each tile that went into the fringe. local cameFrom = Table() -- Enqueue start as the first tile to have its neighbors searched. fringe:insert(start); -- keep exploring neighbors of neighbors... until there are no more. while #fringe > 0 do -- the tile we are currently exploring. local inspect = fringe:popFront(); -- cycle through the tile's neighbors. for i, neighbor in ipairs(inspect:getNeighbors()) do -- if we found the goal, we have the path! if neighbor == goal then -- Follow the path backward to the start from the goal and return it. local path = Table(goal) -- Starting at the tile we are currently at, insert them retracing our steps till we get to the starting tile while inspect ~= start do path:pushFront(inspect) inspect = cameFrom[inspect.id] end return path; end -- else we did not find the goal, so enqueue this tile's neighbors to be inspected -- if the tile exists, has not been explored or added to the fringe yet, and it is pathable if neighbor and not cameFrom[neighbor.id] and neighbor:isPathable() then -- add it to the tiles to be explored and add where it came from for path reconstruction. fringe:insert(neighbor) cameFrom[neighbor.id] = inspect end end end -- if we got here, no path was found return Table() end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you need additional functions for your AI you can add them here -- <<-- /Creer-Merge: functions -->> return AI
mit
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Bozack.lua
38
1036
----------------------------------- -- Area: Windurst Woods -- NPC: Bozack -- Type: Event Replayer -- @zone: 241 -- @pos 92.591 -5.58 -31.529 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0264); 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
libretro/RetroArch
libretro-db/lua/tests.lua
44
2401
local testlib = require 'testlib' local DB_FILE = "/tmp/tmp.rdb" local function create_db(data) local i = 1; testlib.create_db(DB_FILE, function() if i > #data then return end res = data[i] i = i + 1 return res end) local db, err = testlib.RarchDB(DB_FILE) if err then error(err) end return db end local function assert_equals(a, b) if type(a) ~= type(b) then return false end if type(a) == "table" then for k, v in pairs(a) do if not assert_equals(v, b[k]) then return end end return else return assert(a == b, tostring(a) .. " != " .. tostring(b)) end end function query_test(data, result, query) return function() local db = create_db(data) local c, err = db:query(query) if err then error(err) end local i = 0 for item in c:iter() do i = i + 1 assert_equals(item, data[i]) end assert(i == #result, "expected " .. tostring(#result) .. " results got " .. tostring(i)) end end tests = { test_list_all = function() data = { {field=true}, {field=false}, } local db = create_db(data) local c = db:list_all() local i = 1 for item in c:iter() do assert_equals(item, data[i]) i = i + 1 end end, test_boolean_field = query_test({{a=true},{a=false}}, {{a=true}}, "{a:true}"), test_number_field = query_test({{a=3}, {a=4}}, {{a=3}}, "{'a':3}"), test_empty_query = query_test({{a=3}, {a=4}}, {{a=3}, {a=4}}, " {} "), test_string_field = query_test({{a="test"}, {a=4}}, {{a="test"}}, "{'a':'test'}"), test_or_operator = query_test({{a="test"}, {a=4}, {a=5}}, {{a="test"}, {a=4}}, "{'a':or('test', 4)}"), test_or_between = query_test({{a="test"}, {a=4}, {a=5}, {}}, {{a="test"}, {a=4}, {a=5}}, "{'a':or('test', between(2, 7))}"), test_glob = query_test({{a="abc"}, {a="acd"}}, {{a="abc"}}, "{'a':glob('*b*')}"), test_root_function = query_test({{a=1}, {b=4}, {a=5}, {}}, {{a=1}, {b=4}}, "or({a:1},{b:4})"), } for name, cb in pairs(tests) do local ok, err = pcall(cb) if ok then print("V", name) else print("X", name, ":", err) end end
gpl-3.0
kitala1/darkstar
scripts/zones/North_Gustaberg/npcs/Waterfall_Base.lua
34
1403
----------------------------------- -- Area: North Gustaberg -- NPC: Waterfall Base -- Involved In Quest: Drachenfall -- @pos -217.594 98.644 464.722 106 ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local BrassCanteen = trade:hasItemQty(493,1); if (BrassCanteen == true and count == 1) then player:tradeComplete(); player:addItem(492); player:messageSpecial(ITEM_OBTAINED,492); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(REACH_WATER_FROM_HERE); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Al_Zahbi/npcs/Numaaf.lua
53
2294
----------------------------------- -- Area: Al Zahbi -- NPC: Numaaf -- Type: Cooking Normal/Adv. Image Support -- @pos 54.966 -7 8.328 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local guildMember = isGuildMember(player,4); if (guildMember == 1) then if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then if (player:hasStatusEffect(EFFECT_COOKING_IMAGERY) == false) then player:tradeComplete(); player:startEvent(0x00DF,8,0,0,0,188,0,8,0); else npc:showText(npc, IMAGE_SUPPORT_ACTIVE); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,4); local SkillLevel = player:getSkillLevel(SKILL_COOKING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_COOKING_IMAGERY) == false) then player:startEvent(0x00DE,8,SkillLevel,0,511,188,0,8,2184); else player:startEvent(0x00DE,8,SkillLevel,0,511,188,7121,8,2184); end else player:startEvent(0x00DE,0,0,0,0,0,0,8,0); -- Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00DE and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,8,1); player:addStatusEffect(EFFECT_COOKING_IMAGERY,1,0,120); elseif (csid == 0x00DF) then player:messageSpecial(IMAGE_SUPPORT,0,8,0); player:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,480); end end;
gpl-3.0
khwangster/wrk2
deps/luajit/dynasm/dasm_ppc.lua
61
37064
------------------------------------------------------------------------------ -- DynASM PPC module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "ppc", description = "DynASM PPC module", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local tohex = bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0xffffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp = "r1" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r1" then return "sp" end return s end local map_cond = { lt = 0, gt = 1, eq = 2, so = 3, ge = 4, le = 5, ne = 6, ns = 7, } ------------------------------------------------------------------------------ -- Template strings for PPC instructions. local map_op = { tdi_3 = "08000000ARI", twi_3 = "0c000000ARI", mulli_3 = "1c000000RRI", subfic_3 = "20000000RRI", cmplwi_3 = "28000000XRU", cmplwi_2 = "28000000-RU", cmpldi_3 = "28200000XRU", cmpldi_2 = "28200000-RU", cmpwi_3 = "2c000000XRI", cmpwi_2 = "2c000000-RI", cmpdi_3 = "2c200000XRI", cmpdi_2 = "2c200000-RI", addic_3 = "30000000RRI", ["addic._3"] = "34000000RRI", addi_3 = "38000000RR0I", li_2 = "38000000RI", la_2 = "38000000RD", addis_3 = "3c000000RR0I", lis_2 = "3c000000RI", lus_2 = "3c000000RU", bc_3 = "40000000AAK", bcl_3 = "40000001AAK", bdnz_1 = "42000000K", bdz_1 = "42400000K", sc_0 = "44000000", b_1 = "48000000J", bl_1 = "48000001J", rlwimi_5 = "50000000RR~AAA.", rlwinm_5 = "54000000RR~AAA.", rlwnm_5 = "5c000000RR~RAA.", ori_3 = "60000000RR~U", nop_0 = "60000000", oris_3 = "64000000RR~U", xori_3 = "68000000RR~U", xoris_3 = "6c000000RR~U", ["andi._3"] = "70000000RR~U", ["andis._3"] = "74000000RR~U", lwz_2 = "80000000RD", lwzu_2 = "84000000RD", lbz_2 = "88000000RD", lbzu_2 = "8c000000RD", stw_2 = "90000000RD", stwu_2 = "94000000RD", stb_2 = "98000000RD", stbu_2 = "9c000000RD", lhz_2 = "a0000000RD", lhzu_2 = "a4000000RD", lha_2 = "a8000000RD", lhau_2 = "ac000000RD", sth_2 = "b0000000RD", sthu_2 = "b4000000RD", lmw_2 = "b8000000RD", stmw_2 = "bc000000RD", lfs_2 = "c0000000FD", lfsu_2 = "c4000000FD", lfd_2 = "c8000000FD", lfdu_2 = "cc000000FD", stfs_2 = "d0000000FD", stfsu_2 = "d4000000FD", stfd_2 = "d8000000FD", stfdu_2 = "dc000000FD", ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4. ldu_2 = "e8000001RD", lwa_2 = "e8000002RD", std_2 = "f8000000RD", stdu_2 = "f8000001RD", -- Primary opcode 19: mcrf_2 = "4c000000XX", isync_0 = "4c00012c", crnor_3 = "4c000042CCC", crnot_2 = "4c000042CC=", crandc_3 = "4c000102CCC", crxor_3 = "4c000182CCC", crclr_1 = "4c000182C==", crnand_3 = "4c0001c2CCC", crand_3 = "4c000202CCC", creqv_3 = "4c000242CCC", crset_1 = "4c000242C==", crorc_3 = "4c000342CCC", cror_3 = "4c000382CCC", crmove_2 = "4c000382CC=", bclr_2 = "4c000020AA", bclrl_2 = "4c000021AA", bcctr_2 = "4c000420AA", bcctrl_2 = "4c000421AA", blr_0 = "4e800020", blrl_0 = "4e800021", bctr_0 = "4e800420", bctrl_0 = "4e800421", -- Primary opcode 31: cmpw_3 = "7c000000XRR", cmpw_2 = "7c000000-RR", cmpd_3 = "7c200000XRR", cmpd_2 = "7c200000-RR", tw_3 = "7c000008ARR", subfc_3 = "7c000010RRR.", subc_3 = "7c000010RRR~.", mulhdu_3 = "7c000012RRR.", addc_3 = "7c000014RRR.", mulhwu_3 = "7c000016RRR.", isel_4 = "7c00001eRRRC", isellt_3 = "7c00001eRRR", iselgt_3 = "7c00005eRRR", iseleq_3 = "7c00009eRRR", mfcr_1 = "7c000026R", mfocrf_2 = "7c100026RG", mtcrf_2 = "7c000120GR", mtocrf_2 = "7c100120GR", lwarx_3 = "7c000028RR0R", ldx_3 = "7c00002aRR0R", lwzx_3 = "7c00002eRR0R", slw_3 = "7c000030RR~R.", cntlzw_2 = "7c000034RR~", sld_3 = "7c000036RR~R.", and_3 = "7c000038RR~R.", cmplw_3 = "7c000040XRR", cmplw_2 = "7c000040-RR", cmpld_3 = "7c200040XRR", cmpld_2 = "7c200040-RR", subf_3 = "7c000050RRR.", sub_3 = "7c000050RRR~.", ldux_3 = "7c00006aRR0R", dcbst_2 = "7c00006c-RR", lwzux_3 = "7c00006eRR0R", cntlzd_2 = "7c000074RR~", andc_3 = "7c000078RR~R.", td_3 = "7c000088ARR", mulhd_3 = "7c000092RRR.", mulhw_3 = "7c000096RRR.", ldarx_3 = "7c0000a8RR0R", dcbf_2 = "7c0000ac-RR", lbzx_3 = "7c0000aeRR0R", neg_2 = "7c0000d0RR.", lbzux_3 = "7c0000eeRR0R", popcntb_2 = "7c0000f4RR~", not_2 = "7c0000f8RR~%.", nor_3 = "7c0000f8RR~R.", subfe_3 = "7c000110RRR.", sube_3 = "7c000110RRR~.", adde_3 = "7c000114RRR.", stdx_3 = "7c00012aRR0R", stwcx_3 = "7c00012cRR0R.", stwx_3 = "7c00012eRR0R", prtyw_2 = "7c000134RR~", stdux_3 = "7c00016aRR0R", stwux_3 = "7c00016eRR0R", prtyd_2 = "7c000174RR~", subfze_2 = "7c000190RR.", addze_2 = "7c000194RR.", stdcx_3 = "7c0001acRR0R.", stbx_3 = "7c0001aeRR0R", subfme_2 = "7c0001d0RR.", mulld_3 = "7c0001d2RRR.", addme_2 = "7c0001d4RR.", mullw_3 = "7c0001d6RRR.", dcbtst_2 = "7c0001ec-RR", stbux_3 = "7c0001eeRR0R", add_3 = "7c000214RRR.", dcbt_2 = "7c00022c-RR", lhzx_3 = "7c00022eRR0R", eqv_3 = "7c000238RR~R.", eciwx_3 = "7c00026cRR0R", lhzux_3 = "7c00026eRR0R", xor_3 = "7c000278RR~R.", mfspefscr_1 = "7c0082a6R", mfxer_1 = "7c0102a6R", mflr_1 = "7c0802a6R", mfctr_1 = "7c0902a6R", lwax_3 = "7c0002aaRR0R", lhax_3 = "7c0002aeRR0R", mftb_1 = "7c0c42e6R", mftbu_1 = "7c0d42e6R", lwaux_3 = "7c0002eaRR0R", lhaux_3 = "7c0002eeRR0R", sthx_3 = "7c00032eRR0R", orc_3 = "7c000338RR~R.", ecowx_3 = "7c00036cRR0R", sthux_3 = "7c00036eRR0R", or_3 = "7c000378RR~R.", mr_2 = "7c000378RR~%.", divdu_3 = "7c000392RRR.", divwu_3 = "7c000396RRR.", mtspefscr_1 = "7c0083a6R", mtxer_1 = "7c0103a6R", mtlr_1 = "7c0803a6R", mtctr_1 = "7c0903a6R", dcbi_2 = "7c0003ac-RR", nand_3 = "7c0003b8RR~R.", divd_3 = "7c0003d2RRR.", divw_3 = "7c0003d6RRR.", cmpb_3 = "7c0003f8RR~R.", mcrxr_1 = "7c000400X", subfco_3 = "7c000410RRR.", subco_3 = "7c000410RRR~.", addco_3 = "7c000414RRR.", ldbrx_3 = "7c000428RR0R", lswx_3 = "7c00042aRR0R", lwbrx_3 = "7c00042cRR0R", lfsx_3 = "7c00042eFR0R", srw_3 = "7c000430RR~R.", srd_3 = "7c000436RR~R.", subfo_3 = "7c000450RRR.", subo_3 = "7c000450RRR~.", lfsux_3 = "7c00046eFR0R", lswi_3 = "7c0004aaRR0A", sync_0 = "7c0004ac", lwsync_0 = "7c2004ac", ptesync_0 = "7c4004ac", lfdx_3 = "7c0004aeFR0R", nego_2 = "7c0004d0RR.", lfdux_3 = "7c0004eeFR0R", subfeo_3 = "7c000510RRR.", subeo_3 = "7c000510RRR~.", addeo_3 = "7c000514RRR.", stdbrx_3 = "7c000528RR0R", stswx_3 = "7c00052aRR0R", stwbrx_3 = "7c00052cRR0R", stfsx_3 = "7c00052eFR0R", stfsux_3 = "7c00056eFR0R", subfzeo_2 = "7c000590RR.", addzeo_2 = "7c000594RR.", stswi_3 = "7c0005aaRR0A", stfdx_3 = "7c0005aeFR0R", subfmeo_2 = "7c0005d0RR.", mulldo_3 = "7c0005d2RRR.", addmeo_2 = "7c0005d4RR.", mullwo_3 = "7c0005d6RRR.", dcba_2 = "7c0005ec-RR", stfdux_3 = "7c0005eeFR0R", addo_3 = "7c000614RRR.", lhbrx_3 = "7c00062cRR0R", sraw_3 = "7c000630RR~R.", srad_3 = "7c000634RR~R.", srawi_3 = "7c000670RR~A.", sradi_3 = "7c000674RR~H.", eieio_0 = "7c0006ac", lfiwax_3 = "7c0006aeFR0R", sthbrx_3 = "7c00072cRR0R", extsh_2 = "7c000734RR~.", extsb_2 = "7c000774RR~.", divduo_3 = "7c000792RRR.", divwou_3 = "7c000796RRR.", icbi_2 = "7c0007ac-RR", stfiwx_3 = "7c0007aeFR0R", extsw_2 = "7c0007b4RR~.", divdo_3 = "7c0007d2RRR.", divwo_3 = "7c0007d6RRR.", dcbz_2 = "7c0007ec-RR", -- Primary opcode 30: rldicl_4 = "78000000RR~HM.", rldicr_4 = "78000004RR~HM.", rldic_4 = "78000008RR~HM.", rldimi_4 = "7800000cRR~HM.", rldcl_4 = "78000010RR~RM.", rldcr_4 = "78000012RR~RM.", -- Primary opcode 59: fdivs_3 = "ec000024FFF.", fsubs_3 = "ec000028FFF.", fadds_3 = "ec00002aFFF.", fsqrts_2 = "ec00002cF-F.", fres_2 = "ec000030F-F.", fmuls_3 = "ec000032FF-F.", frsqrtes_2 = "ec000034F-F.", fmsubs_4 = "ec000038FFFF~.", fmadds_4 = "ec00003aFFFF~.", fnmsubs_4 = "ec00003cFFFF~.", fnmadds_4 = "ec00003eFFFF~.", -- Primary opcode 63: fdiv_3 = "fc000024FFF.", fsub_3 = "fc000028FFF.", fadd_3 = "fc00002aFFF.", fsqrt_2 = "fc00002cF-F.", fsel_4 = "fc00002eFFFF~.", fre_2 = "fc000030F-F.", fmul_3 = "fc000032FF-F.", frsqrte_2 = "fc000034F-F.", fmsub_4 = "fc000038FFFF~.", fmadd_4 = "fc00003aFFFF~.", fnmsub_4 = "fc00003cFFFF~.", fnmadd_4 = "fc00003eFFFF~.", fcmpu_3 = "fc000000XFF", fcpsgn_3 = "fc000010FFF.", fcmpo_3 = "fc000040XFF", mtfsb1_1 = "fc00004cA", fneg_2 = "fc000050F-F.", mcrfs_2 = "fc000080XX", mtfsb0_1 = "fc00008cA", fmr_2 = "fc000090F-F.", frsp_2 = "fc000018F-F.", fctiw_2 = "fc00001cF-F.", fctiwz_2 = "fc00001eF-F.", mtfsfi_2 = "fc00010cAA", -- NYI: upshift. fnabs_2 = "fc000110F-F.", fabs_2 = "fc000210F-F.", frin_2 = "fc000310F-F.", friz_2 = "fc000350F-F.", frip_2 = "fc000390F-F.", frim_2 = "fc0003d0F-F.", mffs_1 = "fc00048eF.", -- NYI: mtfsf, mtfsb0, mtfsb1. fctid_2 = "fc00065cF-F.", fctidz_2 = "fc00065eF-F.", fcfid_2 = "fc00069cF-F.", -- Primary opcode 4, SPE APU extension: evaddw_3 = "10000200RRR", evaddiw_3 = "10000202RAR~", evsubw_3 = "10000204RRR~", evsubiw_3 = "10000206RAR~", evabs_2 = "10000208RR", evneg_2 = "10000209RR", evextsb_2 = "1000020aRR", evextsh_2 = "1000020bRR", evrndw_2 = "1000020cRR", evcntlzw_2 = "1000020dRR", evcntlsw_2 = "1000020eRR", brinc_3 = "1000020fRRR", evand_3 = "10000211RRR", evandc_3 = "10000212RRR", evxor_3 = "10000216RRR", evor_3 = "10000217RRR", evmr_2 = "10000217RR=", evnor_3 = "10000218RRR", evnot_2 = "10000218RR=", eveqv_3 = "10000219RRR", evorc_3 = "1000021bRRR", evnand_3 = "1000021eRRR", evsrwu_3 = "10000220RRR", evsrws_3 = "10000221RRR", evsrwiu_3 = "10000222RRA", evsrwis_3 = "10000223RRA", evslw_3 = "10000224RRR", evslwi_3 = "10000226RRA", evrlw_3 = "10000228RRR", evsplati_2 = "10000229RS", evrlwi_3 = "1000022aRRA", evsplatfi_2 = "1000022bRS", evmergehi_3 = "1000022cRRR", evmergelo_3 = "1000022dRRR", evcmpgtu_3 = "10000230XRR", evcmpgtu_2 = "10000230-RR", evcmpgts_3 = "10000231XRR", evcmpgts_2 = "10000231-RR", evcmpltu_3 = "10000232XRR", evcmpltu_2 = "10000232-RR", evcmplts_3 = "10000233XRR", evcmplts_2 = "10000233-RR", evcmpeq_3 = "10000234XRR", evcmpeq_2 = "10000234-RR", evsel_4 = "10000278RRRW", evsel_3 = "10000278RRR", evfsadd_3 = "10000280RRR", evfssub_3 = "10000281RRR", evfsabs_2 = "10000284RR", evfsnabs_2 = "10000285RR", evfsneg_2 = "10000286RR", evfsmul_3 = "10000288RRR", evfsdiv_3 = "10000289RRR", evfscmpgt_3 = "1000028cXRR", evfscmpgt_2 = "1000028c-RR", evfscmplt_3 = "1000028dXRR", evfscmplt_2 = "1000028d-RR", evfscmpeq_3 = "1000028eXRR", evfscmpeq_2 = "1000028e-RR", evfscfui_2 = "10000290R-R", evfscfsi_2 = "10000291R-R", evfscfuf_2 = "10000292R-R", evfscfsf_2 = "10000293R-R", evfsctui_2 = "10000294R-R", evfsctsi_2 = "10000295R-R", evfsctuf_2 = "10000296R-R", evfsctsf_2 = "10000297R-R", evfsctuiz_2 = "10000298R-R", evfsctsiz_2 = "1000029aR-R", evfststgt_3 = "1000029cXRR", evfststgt_2 = "1000029c-RR", evfststlt_3 = "1000029dXRR", evfststlt_2 = "1000029d-RR", evfststeq_3 = "1000029eXRR", evfststeq_2 = "1000029e-RR", efsadd_3 = "100002c0RRR", efssub_3 = "100002c1RRR", efsabs_2 = "100002c4RR", efsnabs_2 = "100002c5RR", efsneg_2 = "100002c6RR", efsmul_3 = "100002c8RRR", efsdiv_3 = "100002c9RRR", efscmpgt_3 = "100002ccXRR", efscmpgt_2 = "100002cc-RR", efscmplt_3 = "100002cdXRR", efscmplt_2 = "100002cd-RR", efscmpeq_3 = "100002ceXRR", efscmpeq_2 = "100002ce-RR", efscfd_2 = "100002cfR-R", efscfui_2 = "100002d0R-R", efscfsi_2 = "100002d1R-R", efscfuf_2 = "100002d2R-R", efscfsf_2 = "100002d3R-R", efsctui_2 = "100002d4R-R", efsctsi_2 = "100002d5R-R", efsctuf_2 = "100002d6R-R", efsctsf_2 = "100002d7R-R", efsctuiz_2 = "100002d8R-R", efsctsiz_2 = "100002daR-R", efststgt_3 = "100002dcXRR", efststgt_2 = "100002dc-RR", efststlt_3 = "100002ddXRR", efststlt_2 = "100002dd-RR", efststeq_3 = "100002deXRR", efststeq_2 = "100002de-RR", efdadd_3 = "100002e0RRR", efdsub_3 = "100002e1RRR", efdcfuid_2 = "100002e2R-R", efdcfsid_2 = "100002e3R-R", efdabs_2 = "100002e4RR", efdnabs_2 = "100002e5RR", efdneg_2 = "100002e6RR", efdmul_3 = "100002e8RRR", efddiv_3 = "100002e9RRR", efdctuidz_2 = "100002eaR-R", efdctsidz_2 = "100002ebR-R", efdcmpgt_3 = "100002ecXRR", efdcmpgt_2 = "100002ec-RR", efdcmplt_3 = "100002edXRR", efdcmplt_2 = "100002ed-RR", efdcmpeq_3 = "100002eeXRR", efdcmpeq_2 = "100002ee-RR", efdcfs_2 = "100002efR-R", efdcfui_2 = "100002f0R-R", efdcfsi_2 = "100002f1R-R", efdcfuf_2 = "100002f2R-R", efdcfsf_2 = "100002f3R-R", efdctui_2 = "100002f4R-R", efdctsi_2 = "100002f5R-R", efdctuf_2 = "100002f6R-R", efdctsf_2 = "100002f7R-R", efdctuiz_2 = "100002f8R-R", efdctsiz_2 = "100002faR-R", efdtstgt_3 = "100002fcXRR", efdtstgt_2 = "100002fc-RR", efdtstlt_3 = "100002fdXRR", efdtstlt_2 = "100002fd-RR", efdtsteq_3 = "100002feXRR", efdtsteq_2 = "100002fe-RR", evlddx_3 = "10000300RR0R", evldd_2 = "10000301R8", evldwx_3 = "10000302RR0R", evldw_2 = "10000303R8", evldhx_3 = "10000304RR0R", evldh_2 = "10000305R8", evlwhex_3 = "10000310RR0R", evlwhe_2 = "10000311R4", evlwhoux_3 = "10000314RR0R", evlwhou_2 = "10000315R4", evlwhosx_3 = "10000316RR0R", evlwhos_2 = "10000317R4", evstddx_3 = "10000320RR0R", evstdd_2 = "10000321R8", evstdwx_3 = "10000322RR0R", evstdw_2 = "10000323R8", evstdhx_3 = "10000324RR0R", evstdh_2 = "10000325R8", evstwhex_3 = "10000330RR0R", evstwhe_2 = "10000331R4", evstwhox_3 = "10000334RR0R", evstwho_2 = "10000335R4", evstwwex_3 = "10000338RR0R", evstwwe_2 = "10000339R4", evstwwox_3 = "1000033cRR0R", evstwwo_2 = "1000033dR4", evmhessf_3 = "10000403RRR", evmhossf_3 = "10000407RRR", evmheumi_3 = "10000408RRR", evmhesmi_3 = "10000409RRR", evmhesmf_3 = "1000040bRRR", evmhoumi_3 = "1000040cRRR", evmhosmi_3 = "1000040dRRR", evmhosmf_3 = "1000040fRRR", evmhessfa_3 = "10000423RRR", evmhossfa_3 = "10000427RRR", evmheumia_3 = "10000428RRR", evmhesmia_3 = "10000429RRR", evmhesmfa_3 = "1000042bRRR", evmhoumia_3 = "1000042cRRR", evmhosmia_3 = "1000042dRRR", evmhosmfa_3 = "1000042fRRR", evmwhssf_3 = "10000447RRR", evmwlumi_3 = "10000448RRR", evmwhumi_3 = "1000044cRRR", evmwhsmi_3 = "1000044dRRR", evmwhsmf_3 = "1000044fRRR", evmwssf_3 = "10000453RRR", evmwumi_3 = "10000458RRR", evmwsmi_3 = "10000459RRR", evmwsmf_3 = "1000045bRRR", evmwhssfa_3 = "10000467RRR", evmwlumia_3 = "10000468RRR", evmwhumia_3 = "1000046cRRR", evmwhsmia_3 = "1000046dRRR", evmwhsmfa_3 = "1000046fRRR", evmwssfa_3 = "10000473RRR", evmwumia_3 = "10000478RRR", evmwsmia_3 = "10000479RRR", evmwsmfa_3 = "1000047bRRR", evmra_2 = "100004c4RR", evdivws_3 = "100004c6RRR", evdivwu_3 = "100004c7RRR", evmwssfaa_3 = "10000553RRR", evmwumiaa_3 = "10000558RRR", evmwsmiaa_3 = "10000559RRR", evmwsmfaa_3 = "1000055bRRR", evmwssfan_3 = "100005d3RRR", evmwumian_3 = "100005d8RRR", evmwsmian_3 = "100005d9RRR", evmwsmfan_3 = "100005dbRRR", evmergehilo_3 = "1000022eRRR", evmergelohi_3 = "1000022fRRR", evlhhesplatx_3 = "10000308RR0R", evlhhesplat_2 = "10000309R2", evlhhousplatx_3 = "1000030cRR0R", evlhhousplat_2 = "1000030dR2", evlhhossplatx_3 = "1000030eRR0R", evlhhossplat_2 = "1000030fR2", evlwwsplatx_3 = "10000318RR0R", evlwwsplat_2 = "10000319R4", evlwhsplatx_3 = "1000031cRR0R", evlwhsplat_2 = "1000031dR4", evaddusiaaw_2 = "100004c0RR", evaddssiaaw_2 = "100004c1RR", evsubfusiaaw_2 = "100004c2RR", evsubfssiaaw_2 = "100004c3RR", evaddumiaaw_2 = "100004c8RR", evaddsmiaaw_2 = "100004c9RR", evsubfumiaaw_2 = "100004caRR", evsubfsmiaaw_2 = "100004cbRR", evmheusiaaw_3 = "10000500RRR", evmhessiaaw_3 = "10000501RRR", evmhessfaaw_3 = "10000503RRR", evmhousiaaw_3 = "10000504RRR", evmhossiaaw_3 = "10000505RRR", evmhossfaaw_3 = "10000507RRR", evmheumiaaw_3 = "10000508RRR", evmhesmiaaw_3 = "10000509RRR", evmhesmfaaw_3 = "1000050bRRR", evmhoumiaaw_3 = "1000050cRRR", evmhosmiaaw_3 = "1000050dRRR", evmhosmfaaw_3 = "1000050fRRR", evmhegumiaa_3 = "10000528RRR", evmhegsmiaa_3 = "10000529RRR", evmhegsmfaa_3 = "1000052bRRR", evmhogumiaa_3 = "1000052cRRR", evmhogsmiaa_3 = "1000052dRRR", evmhogsmfaa_3 = "1000052fRRR", evmwlusiaaw_3 = "10000540RRR", evmwlssiaaw_3 = "10000541RRR", evmwlumiaaw_3 = "10000548RRR", evmwlsmiaaw_3 = "10000549RRR", evmheusianw_3 = "10000580RRR", evmhessianw_3 = "10000581RRR", evmhessfanw_3 = "10000583RRR", evmhousianw_3 = "10000584RRR", evmhossianw_3 = "10000585RRR", evmhossfanw_3 = "10000587RRR", evmheumianw_3 = "10000588RRR", evmhesmianw_3 = "10000589RRR", evmhesmfanw_3 = "1000058bRRR", evmhoumianw_3 = "1000058cRRR", evmhosmianw_3 = "1000058dRRR", evmhosmfanw_3 = "1000058fRRR", evmhegumian_3 = "100005a8RRR", evmhegsmian_3 = "100005a9RRR", evmhegsmfan_3 = "100005abRRR", evmhogumian_3 = "100005acRRR", evmhogsmian_3 = "100005adRRR", evmhogsmfan_3 = "100005afRRR", evmwlusianw_3 = "100005c0RRR", evmwlssianw_3 = "100005c1RRR", evmwlumianw_3 = "100005c8RRR", evmwlsmianw_3 = "100005c9RRR", -- NYI: Book E instructions. } -- Add mnemonics for "." variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "." then local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2) t[sub(k, 1, -3).."."..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end -- Add more branch mnemonics. for cond,c in pairs(map_cond) do local b1 = "b"..cond local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0) -- bX[l] map_op[b1.."_1"] = tohex(0x40800000 + c1).."K" map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K" map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K" map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK" map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK" map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK" -- bXlr[l] map_op[b1.."lr_0"] = tohex(0x4c800020 + c1) map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1) map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1) map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1) -- bXctr[l] map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X" map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X" map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X" map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X" end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_cr(expr) local r = match(expr, "^cr([0-7])$") if r then return tonumber(r) end werror("bad condition register name `"..expr.."'") end local function parse_cond(expr) local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$") if r then r = tonumber(r) local c = map_cond[cond] if c and c < 4 then return r*4+c end end werror("bad condition bit name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") elseif match(imm, "^r([1-3]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_shiftmask(imm, isshift) local n = tonumber(imm) if n then if shr(n, 6) == 0 then local lsb = band(imm, 31) local msb = imm - lsb return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb) end werror("out of range immediate `"..imm.."'") elseif match(imm, "^r([1-3]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else werror("NYI: parameterized 64 bit shift/mask") end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 16, 0, 0, true) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") end local function parse_u5disp(disp, scale) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 5, 11, scale, false) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n, rs = 1, 26 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions (rlwinm). if secpos+3 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "R" then rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1 elseif p == "F" then rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1 elseif p == "A" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1 elseif p == "S" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "D" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "2" then op = op + parse_u5disp(params[n], 1); n = n + 1 elseif p == "4" then op = op + parse_u5disp(params[n], 2); n = n + 1 elseif p == "8" then op = op + parse_u5disp(params[n], 3); n = n + 1 elseif p == "C" then rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1 elseif p == "X" then rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1 elseif p == "W" then op = op + parse_cr(params[n]); n = n + 1 elseif p == "G" then op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1 elseif p == "H" then op = op + parse_shiftmask(params[n], true); n = n + 1 elseif p == "M" then op = op + parse_shiftmask(params[n], false); n = n + 1 elseif p == "J" or p == "K" then local mode, n, s = parse_label(params[n], false) if p == "K" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "0" then if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end elseif p == "=" or p == "%" then local t = band(shr(op, p == "%" and rs+5 or rs), 31) rs = rs - 5 op = op + shl(t, rs) elseif p == "~" then local mm = shl(31, rs) local lo = band(op, mm) local hi = band(op, shl(mm, 5)) op = op - lo - hi + shl(lo, 5) + shr(hi, 5) elseif p == "-" then rs = rs - 5 elseif p == "." then -- Ignored. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
apache-2.0
kitala1/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Louxiard.lua
16
2281
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Louxiard -- @zone 80 -- @pos -93 -4 49 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 3) then if(trade:hasItemQty(2528,1) and trade:getItemCount() == 1) then player:startEvent(0x01A) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_AVAILABLE and player:getMainLvl() >= 10) then player:startEvent(0x015); -- Gifts of Griffon Quest Start elseif(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 0) then player:startEvent(0x016); -- Gifts of Griffon Stage 2 Cutscene elseif (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 1) then player:startEvent(0x027); -- Gifts of Griffon Stage 2 Dialogue else player:startEvent(0x025); -- Default Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x015) then player:addQuest(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON); -- Gifts of Griffon Quest Start elseif(csid == 0x016) then player:setVar("GiftsOfGriffonProg",1); -- Gifts of Griffon Stage 2 elseif(csid == 0x01A) then player:tradeComplete(); player:setVar("GiftsOfGriffonProg",4); -- Gifts of Griffon Stage 3 end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/meat_mithkabob.lua
35
1460
----------------------------------------- -- ID: 4381 -- Item: meat_mithkabob -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength 5 -- Agility 1 -- Intelligence -2 -- Attack % 22 -- Attack Cap 60 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4381); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 60); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 60); end;
gpl-3.0
d-o/LUA-LIB
K400Examples/remotes/D840_ethernet.lua
2
2611
#!/usr/bin/env lua ------------------------------------------------------------------------------- -- Example for using the D840 via ethernet. -- ------------------------------------------------------------------------------- --============================================================================= -- Some of the more commonly used modules as globals local rinApp = require 'rinApp' -- load in the application framework local timers = require 'rinSystem.rinTimers' -- load in some system timers local dbg = require 'rinLibrary.rinDebug' -- load in a debugger --============================================================================= -- Connect to the instrument you want to control local device = rinApp.addK400() -- local K401 instrumentH -- Load the remote display. An extra ip addess option is supplied here to -- connect using ethernet. device.addDisplay("D840", "d840", "172.17.1.180") -- Loop function local function looper() -- Write a long string and some units. device.write("D840", "123456789 hello") device.writeUnits("D840", 't') -- Write the same text and some units to the top left device.write("topLeft", "123456789 hello") device.writeUnits("topLeft", 't', 'per_h') -- Write the same text and some units to the bottom left device.write("bottomLeft", "123456789 hello") device.writeUnits("bottomLeft", 't', 'per_h') -- Turn on some annunciators. device.setAnnunciators('topLeft', 'battery') device.setAnnunciators('bottomLeft', 'clock') -- Wait for 3 seconds rinApp.delay(3) -- Turn on some annunciators on the remote display. -- The red and green lights can be turned on simultaneously. device.setAnnunciators("D840", 'net', 'coz', 'redLight', 'greenLight') -- Wait for 3 seconds rinApp.delay(3) -- Turn off some annunciators on the remote display. device.clearAnnunciators('D840', 'net', 'coz', 'redLight', 'greenLight') -- Flash the green light. device.setAnnunciators("D840", 'greenLight') rinApp.delay(2) device.clearAnnunciators("D840", 'greenLight') -- Flash the red light. device.setAnnunciators("D840", 'redLight') rinApp.delay(2) device.clearAnnunciators("D840", 'redLight') -- Flash the green and red light. device.setAnnunciators("D840", 'greenLight', 'redLight') rinApp.delay(2) device.clearAnnunciators("D840", 'greenLight', 'redLight') -- Clear the remote display device.write("D840", "") device.writeUnits("D840", 'none') -- Wait for 3 seconds rinApp.delay(3) end rinApp.setMainLoop(looper) rinApp.run()
gpl-3.0
kitala1/darkstar
scripts/zones/Nashmau/npcs/Jajaroon.lua
34
1593
----------------------------------- -- Area: Nashmau -- NPC: Jajaroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,JAJAROON_SHOP_DIALOG); stock = {0x0880,48, -- Fire Card 0x0881,48, -- Ice Card 0x0882,48, -- Wind Card 0x0883,48, -- Earth Card 0x0884,48, -- Thunder Card 0x0885,48, -- Water Card 0x0886,48, -- Light Card 0x0887,48, -- Dark Card 0x16ee,10000, -- Trump Card Case 0x1570,35200, -- Samurai Die 0x1571,600, -- Ninja Die 0x1572,82500, -- Dragoon Die 0x1573,40000, -- Summoner Die 0x1574,3525, -- Blue Mage Die 0x1575,316, -- Corsar Die 0x1576,9216} -- Puppetmaster Die showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/bowl_of_pumpkin_soup.lua
35
1656
----------------------------------------- -- ID: 4430 -- Item: bowl_of_pumpkin_soup -- Food Effect: 3Hrs, All Races ----------------------------------------- -- HP % 1 -- Vitality -1 -- Agility 3 -- HP Recovered While Healing 5 -- Ranged Accuracy % 8 (cap 20) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4430); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 1); target:addMod(MOD_FOOD_HP_CAP, 999); target:addMod(MOD_VIT, -1); target:addMod(MOD_AGI, 3); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_FOOD_RACCP, 8); target:addMod(MOD_FOOD_RACC_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 1); target:delMod(MOD_FOOD_HP_CAP, 999); target:delMod(MOD_VIT, -1); target:delMod(MOD_AGI, 3); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_FOOD_RACCP, 8); target:delMod(MOD_FOOD_RACC_CAP, 20); end;
gpl-3.0
bobbahbrown/pcmod3
lua/pcm3/cl_screen.lua
1
2245
// ************************************ \\ // * PCMod 3 - thomasfn & bobbahbrown * \\ // ************************************ \\ // cl_screen.lua - CLIENTSIDE - Loads the screen object local M = PCMod3.CreateModule( "Screen" ) local obj = PCMod3.CreateBase( "screen" ) M.Screens = {} function M:CallOnAll( funcname, ... ) for _, o in pairs( M.Screens ) do o:Call( funcname, ... ) end end function obj:New() table.insert( M.Screens, self ) self.m_pPanel = PCMod3.Create( "basepanel" ) function self.m_pPanel:Paint( x, y, w, h ) surface.SetDrawColor( 0, 0, 0, 255 ) surface.DrawRect( x, y, w, h ) end end function obj:SetConfig( cfg ) self.m_tConfig = cfg self:PerformLayout() end function obj:SetEntity( ent ) self.m_eEntity = ent end function obj:GetConfig() return self.m_tConfig end function obj:GetDrawBounds() local cfg = self:GetConfig() if (!cfg) then return 0, 0, 0, 0 end return cfg.RX, cfg.RY, cfg.RW, cfg.RH end function obj:PerformLayout() local x, y, w, h = self:GetDrawBounds() self.m_pPanel:SetPos( x, y ) self.m_pPanel:SetSize( w, h ) end function obj:OnRemove() if (self.m_pPanel && self.m_pPanel:IsValid()) then self.m_pPanel:Remove() self.m_pPanel = nil end end local baserotate = Vector( -90, 90, 0 ) function obj:Render() local cfg = self.m_tConfig if (!cfg) then ErrPCM( "Screen failed to render! (No config)" ) return end local ent = self.m_eEntity if (!ent) then ErrPCM( "Screen failed to render! (No entity)" ) return end local origin, ang = ent:GetPos(), ent:GetAngles() local drawpos = origin + (ent:GetForward() * cfg.OffsetForward) + (ent:GetUp() * cfg.OffsetUp) + (ent:GetRight() * cfg.OffsetRight) local rot = baserotate + cfg.Rotation ang:RotateAroundAxis( ang:Right(), rot.x ) ang:RotateAroundAxis( ang:Up(), rot.y ) ang:RotateAroundAxis( ang:Forward(), rot.z ) cam.Start3D2D( drawpos, ang, cfg.Resolution ) self:Draw() cam.End3D2D() end function obj:Draw() local pn = self.m_pPanel if (!pn) then ErrPCM( "Screen failed to draw! (No panel)" ) return end pn:CompletePaint() end function obj:InvalidateLayout() local pn = self.m_pPanel if (!pn) then ErrPCM( "Screen failed to layout! (No panel)" ) return end pn:CompleteLayout() end
mit
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Marin.lua
38
1121
----------------------------------- -- Area: Bastok Markets -- NPC: Marin -- Type: Quest Giver -- @zone: 235 -- @pos -340.060 -11.003 -148.181 -- -- Auto-Script: Requires Verification. Verified standard dialog is also "All By Myself" repeatable quest. - thrydwolf 12/18/2011 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0169); 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
kitala1/darkstar
scripts/zones/Lower_Jeuno/npcs/_l01.lua
36
1563
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -101.010 0 -144.080 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 10) then player:setVar("cService",11); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 23) then player:setVar("cService",24); end end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ZenityRTS/Zenity
ModelMaterials/0_angleshark.lua
1
2249
-- $Id$ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local unitInfo = {} local function DrawUnit(unitid, material, materialID) local info = unitInfo[unitid] if (not info) then info = {dir=0, lx=0, lz=0} unitInfo[unitid] = info end local vx,vy,vz = Spring.GetUnitVelocity(unitid) local speed = (vx*vx+vy*vy+vz*vz)^0.5 local curFrame = Spring.GetGameFrame() if (info.n ~= curFrame) then info.n = curFrame; local lx = info.lx local lz = info.lz local dx,dy,dz = Spring.GetUnitDirection(unitid) info.dir = info.dir*0.95 + (lx*dz - lz*dx) / ( (lx*lx+lz*lz)^0.5 + (dx*dx+dz*dz)^0.5 ); info.lx,info.lz = dx,dz; end gl.Uniform(material.frameLoc, Spring.GetGameFrame()%360) gl.Uniform(material.speedLoc, info.dir,0,speed) return false --// engine should still draw it (we just set the uniforms for the shader) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local materials = { shark = { shader = include("ModelMaterials/Shaders/shark.lua"), force = true, --// always use the shader even when normalmapping is disabled usecamera = false, culling = GL.BACK, texunits = { [0] = '%%UNITDEFID:0', [1] = '%%UNITDEFID:1', [2] = '$shadow', [3] = '$specular', [4] = '$reflection', }, DrawUnit = DrawUnit } } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- affected unitdefs local unitMaterials = { angelshark = "shark", } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return materials, unitMaterials -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
kitala1/darkstar
scripts/zones/Mount_Zhayolm/npcs/Mining_Point.lua
29
1096
----------------------------------- -- Area: Mount Zhayolm -- NPC: Mining Point ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ------------------------------------- require("scripts/globals/mining"); require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startMining(player,player:getZoneID(),npc,trade,0x0099); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
Taracque/epgp
libs/AceGUI-3.0/widgets/AceGUIWidget-Heading.lua
12
2294
--[[----------------------------------------------------------------------------- Heading Widget -------------------------------------------------------------------------------]] local Type, Version = "Heading", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetText() self:SetFullWidth() self:SetHeight(18) end, -- ["OnRelease"] = nil, ["SetText"] = function(self, text) self.label:SetText(text or "") if text and text ~= "" then self.left:SetPoint("RIGHT", self.label, "LEFT", -5, 0) self.right:Show() else self.left:SetPoint("RIGHT", -3, 0) self.right:Hide() end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontNormal") label:SetPoint("TOP") label:SetPoint("BOTTOM") label:SetJustifyH("CENTER") local left = frame:CreateTexture(nil, "BACKGROUND") left:SetHeight(8) left:SetPoint("LEFT", 3, 0) left:SetPoint("RIGHT", label, "LEFT", -5, 0) left:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") left:SetTexCoord(0.81, 0.94, 0.5, 1) local right = frame:CreateTexture(nil, "BACKGROUND") right:SetHeight(8) right:SetPoint("RIGHT", -3, 0) right:SetPoint("LEFT", label, "RIGHT", 5, 0) right:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") right:SetTexCoord(0.81, 0.94, 0.5, 1) local widget = { label = label, left = left, right = right, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
bsd-3-clause
kitala1/darkstar
scripts/zones/Bastok_Mines/npcs/Medicine_Eagle.lua
19
1474
----------------------------------- -- Area: Bastok Mines -- NPC: Medicine Eagle -- Involved in Mission: Bastok 6-1, 8-1 -- @pos -40 0 38 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(BASTOK) == RETURN_OF_THE_TALEKEEPER and player:getVar("MissionStatus") == 0) then player:startEvent(0x00b4); else player:startEvent(0x0019); end end; -- if Bastok Mission 8-1 -- 0x00b0 -- player:startEvent(0x00b4); -- player:startEvent(0x00b5); --0x0001 0x0019 0x00b0 0x00b5 0x00b4 ----------------------------------- -- 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 == 0x00b4) then player:setVar("MissionStatus",1); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/sleep_bolt.lua
20
1180
----------------------------------------- -- ID: 18149 -- Item: Sleep Bolt -- Additional Effect: Sleep ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 95; if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local duration = 25; if (target:getMainLvl() > player:getMainLvl()) then duration = duration - (target:getMainLvl() - player:getMainLvl()) end utils.clamp(duration,1,25); duration = duration * applyResistanceAddEffect(player,target,ELE_LIGHT,0); if (not target:hasStatusEffect(EFFECT_SLEEP_I)) then target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration); end return SUBEFFECT_SLEEP, 160, EFFECT_SLEEP_I; end end;
gpl-3.0
gsick/lit-sqlite3
tests/main.lua
1
3156
local sqlite = require("sqlite3") local Path = require("path") local Fs = require("fs") -- remove temp db if Fs.accessSync(Path.join(process.cwd(), "tmp/test.sqlite")) then Fs.unlinkSync(Path.join(process.cwd(), "tmp/test.sqlite")) end -- create a DB local db, err = sqlite.open("tmp/test.sqlite", "read") if not db then assert(err == "unable to open database file") end -- create a DB local db, err = sqlite.open("/root/test.sqlite", "create") if not db then assert(err == "unable to open database file") end -- create a DB local db, err = sqlite.open("tmp/test.sqlite", "create") if not db then p(err) end assert(db ~= nil) -- create a table local users_table_sql = [[ CREATE TABLE IF NOT EXISTS users ( uuid TEXT PRIMARY KEY, login TEXT, password TEXT ); ]] local users2_table_sql = [[ CREATE TABLE users ( uuid TEXT PRIMARY KEY, login TEXT, password TEXT ); ]] local r, err = db:exec(users_table_sql) if r ~= sqlite.OK then p(err) end assert(r == sqlite.OK) local r, err = db:exec(users2_table_sql) if r ~= sqlite.OK then assert(err == "table users already exists") end local r, err = db:close() if r ~= sqlite.OK then p(err) end assert(r == sqlite.OK) -- open a DB local db, err = sqlite.open("tmp/test.sqlite", "write") if not db then p(err) end assert(db ~= nil) local users_insert_sql = [[ INSERT INTO users VALUES(?,?,?); ]] local stmt, err = db:prepare(users_insert_sql) if not stmt then p(err) end assert(stmt ~= nil) local data = { { "uuid-1", "foo", "bar" }, { "uuid-2", "foo2", "bar2" } } local r = true local err local i = 1 while r and i <= #data do local a, b = stmt:bind_values(unpack(data[i])) if a ~= sqlite.OK then p(b) end assert(a == sqlite.OK) r, err = stmt:step() if r ~= true then stmt:reset() r = true end i=i+1 end if r == nil then p(err) end local r, err = stmt:finalize() if r ~= sqlite.OK then p(err) end local stmt, err = db:prepare(users_insert_sql) assert(stmt ~= nil) stmt:bind_values( "uuid-1", "foo", "bar" ) local r, err = stmt:step() if err then -- already exists assert(r == sqlite.CONSTRAINT) assert(err == "UNIQUE constraint failed: users.uuid") end local r, err = stmt:finalize() if err then -- already exists assert(r == sqlite.CONSTRAINT) assert(err == "UNIQUE constraint failed: users.uuid") end local r, err = db:close() if r ~= sqlite.OK then p(err) end local db, err = sqlite.open("tmp/test.sqlite", "read") local stmt, err = db:prepare("SELECT uuid FROM users WHERE login=? AND password=? LIMIT 1") assert(stmt ~= nil) local r, err = stmt:bind_values( "foo", "bar" ) local row = stmt:rows() if row then local r = row() if r then assert(r[1] == "uuid-1") end end local r, err = stmt:finalize() local stmt, err = db:prepare("SELECT uuid FROM users") assert(stmt ~= nil) local row = stmt:rows() if row then local r = row() local i = 1 while r do assert(r[1] == "uuid-" .. i) i = i + 1 r = row() end end local r, err = stmt:finalize() local r, err = db:close() if r ~= sqlite.OK then p(err) end
mit
kitala1/darkstar
scripts/zones/RuAun_Gardens/mobs/Byakko.lua
12
1521
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: Byakko -- ID: 17309982 ----------------------------------- require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:showText(mob,SKY_GOD_OFFSET + 12); GetNPCByID(17310051):hideNPC(120); end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, target, damage) local LV_diff = target:getMainLvl() - mob:getMainLvl(); local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); local ranDmgMod = math.random(0,15) local dmg = INT_diff+LV_diff+ranDmgMod; local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(mob, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(mob,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(mob,target,ELE_LIGHT,dmg); return SUBEFFECT_LIGHT_DAMAGE,163,dmg; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u2.lua
19
1339
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if(npc:getAnimation() == 8) then player:startEvent(0x11); else player:messageSpecial(SD_VERY_SMALL); end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ioiasff/DSA
plugins/admin.lua
381
7085
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "addcontact" and matches[2] then add_contact(matches[2],matches[3],matches[4],ok_cb,false) return "Number "..matches[2].." add from contact list" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](addcontact) (.*) (.*) (.*)$", "^[!/](whois) (%d+)$", "^/(sync_gbans)$"--sync your global bans with seed }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0