content
stringlengths
5
1.05M
local print, tostring, _G, pcall, ipairs, isnumber = print, tostring, _G, pcall, ipairs, isnumber local e, f, g, h, s print('has debug', debug ~= nil) if not debug then error('no debug') end print('----- debug.getfenv, debug.setfenv') f = function(a) return 'f:' .. tostring(a) .. '|' .. tostring(b) end s, e, g = pcall(debug.getfenv, f) print(s, type(e), type(g), (e == G), pcall(f, 'abc')) s, e, g = pcall(debug.setfenv, f, { b = 'def' }) print(s, type(e), type(g), (e == G), pcall(f, 'abc')) s, e, g = pcall(debug.getfenv, f) print(s, type(e), type(g), (e == G), pcall(f, 'abc')) print('----- debug.getlocal, debug.setlocal') h = function(v, i, n) s = 'h-' .. v .. '-' .. i local x1, y1 = debug.getlocal(v, i) local x2, y2 = debug.setlocal(v, i, n) local x3, y3 = debug.getlocal(v, i) return s .. ' -> ' .. v .. '-' .. i .. ' ' .. 'get=' .. tostring(x1) .. ',' .. tostring(y1) .. ' ' .. 'set=' .. tostring(x2) .. ',' .. tostring(y2) .. ' ' .. 'get=' .. tostring(x3) .. ',' .. tostring(y3) .. ' ' end g = function(...) local p, q, r = 7, 8, 9 local t = h(...) local b = table.concat({ ... }, ',') return t .. '\tg locals=' .. p .. ',' .. q .. ',' .. r .. ' tbl={' .. b .. '}' end f = function(a, b, c) local d, e, f = 4, 5, 6 local t = g(a, b, c) return t .. '\tf locals=' .. ',' .. a .. ',' .. b .. ',' .. c .. ',' .. d .. ',' .. e .. ',' .. f end for lvl = 3, 2, -1 do for lcl = 0, 7 do print(pcall(f, lvl, lcl, '#')) end end for lvl = 1, 1 do for lcl = 3, 7 do print(pcall(f, lvl, lcl, '#')) end end print('----- debug.getupvalue, debug.setupvalue') local m, n, o = 101, 102, 103 f = function(p, q, r) local p, q, r = 104, 105, 106 local g = function(s, t, u) local v, w, x = 107, 108, 109 return function() return m, n, o, p, q, r, v, w, x end end return g end g = f() h = g() local callh = function() local t = {} for i, v in ipairs({ pcall(h) }) do t[i] = tostring(v) end return table.concat(t, ',') end print('h', h()) local funs = { f, g, h } local names = { 'f', 'g', 'h' } for i = 1, 3 do local fun, name = funs[i], names[i] for index = 0, 10 do local s1, x1, y1 = pcall(debug.getupvalue, fun, index) local s2, x2, y2 = pcall(debug.setupvalue, fun, index, 666000 + i * 111000 + index) local s3, x3, y3 = pcall(debug.getupvalue, fun, index) print(name .. ' -> ' .. i .. '-' .. index .. ' ' .. 'get=' .. tostring(s1) .. ',' .. tostring(x1) .. ',' .. tostring(y1) .. ' ' .. 'set=' .. tostring(s2) .. ',' .. tostring(x2) .. ',' .. tostring(y2) .. ' ' .. 'get=' .. tostring(s3) .. ',' .. tostring(x3) .. ',' .. tostring(y3) .. ' ' .. 'tbl=' .. callh()) end end print('----- debug.setmetatable, debug.getmetatable') local a = { a = 'bbb' } local b = {} local mt = { __index = { b = 'ccc' } } print('a.a=' .. tostring(a.a) .. ' a.b=' .. tostring(a.b) .. ' b.a=' .. tostring(b.a) .. ' b.b=' .. tostring(b.b)) local s1, x1, y1 = pcall(debug.getmetatable, a) local s2, x2, y2 = pcall(debug.setmetatable, a, mt) print('a.a=' .. tostring(a.a) .. ' a.b=' .. tostring(a.b) .. ' b.a=' .. tostring(b.a) .. ' b.b=' .. tostring(b.b)) local s3, x3, y3 = pcall(debug.getmetatable, a) local s4, x4, y4 = pcall(debug.getmetatable, b) local s5, x5, y5 = pcall(debug.setmetatable, a, nil) print('a.a=' .. tostring(a.a) .. ' a.b=' .. tostring(a.b) .. ' b.a=' .. tostring(b.a) .. ' b.b=' .. tostring(b.b)) local s6, x6, y6 = pcall(debug.getmetatable, a) if not s1 then print('s1 error', x1) end if not s2 then print('s2 error', x2) end if not s3 then print('s3 error', x3) end if not s4 then print('s4 error', x4) end if not s5 then print('s5 error', x5) end if not s6 then print('s6 error', x6) end print('get=' .. tostring(s1) .. ',' .. tostring(x1 == nil) .. ',' .. tostring(y1)) print('set=' .. tostring(s2) .. ',' .. tostring(x2 == a) .. ',' .. tostring(y2)) print('get=' .. tostring(s3) .. ',' .. tostring(x3 == mt) .. ',' .. tostring(y3)) print('get=' .. tostring(s4) .. ',' .. tostring(x4 == nil) .. ',' .. tostring(y4)) print('set=' .. tostring(s5) .. ',' .. tostring(x5 == a) .. ',' .. tostring(y5)) print('get=' .. tostring(s6) .. ',' .. tostring(x6 == nil) .. ',' .. tostring(y6)) print(pcall(debug.getmetatable, 1)) print(pcall(debug.setmetatable, 1, {})) print(pcall(debug.setmetatable, 1, nil)) print('----- debug.getinfo') local printfield = function(tbl, field) local x = tbl[field] if x == nil then return end local typ = type(x) if typ == 'table' then x = '{' .. table.concat(x, ',') .. '}' elseif typ == 'function' then x = typ end print(' ' .. field .. ': ' .. tostring(x)) end local fields = { 'source', 'short_src', 'what', 'currentline', 'linedefined', 'lastlinedefined', 'nups', 'func', 'activelines' } local printinfo = function(...) for i, a in ipairs(arg) do if type(a) == 'table' then for j, field in ipairs(fields) do printfield(a, field) end else print(tostring(a)) end end end function test() local x = 5 function f() x = x + 1 return x end function g() x = x - 1 print('---') printinfo('debug.getinfo(1)', debug.getinfo(1)) printinfo('debug.getinfo(1,"")', debug.getinfo(1, "")) printinfo('debug.getinfo(1,"l")', debug.getinfo(1, "l")) printinfo('debug.getinfo(1,"fL")', debug.getinfo(1, "fL")) printinfo('debug.getinfo(2)', debug.getinfo(2)) printinfo('debug.getinfo(2,"l")', debug.getinfo(2, "l")) printinfo('debug.getinfo(2,"fL")', debug.getinfo(2, "fL")) printinfo('debug.getinfo(10,"")', pcall(debug.getinfo, 10, "")) printinfo('debug.getinfo(-10,"")', pcall(debug.getinfo, -10, "")) --[[ for i=1,3 do printinfo( 'debug.traceback("msg")', debug.traceback('msg') ) printinfo( 'debug.traceback("another",'..i..')', debug.traceback('another',i) ) end --]] print('---') return x end print(f()) print(g()) return f, g end local options = "nSlufL" local e, f, g = pcall(test) print('e,f,g', e, type(f), type(g)) printinfo('debug.getinfo(f)', pcall(debug.getinfo, f)) printinfo('debug.getinfo(f,"' .. options .. '")', pcall(debug.getinfo, f, options)) for j = 1, 6 do local opts = options:sub(j, j) printinfo('debug.getinfo(f,"' .. opts .. '")', pcall(debug.getinfo, f, opts)) end printinfo('debug.getinfo(g)', pcall(debug.getinfo, g)) printinfo('debug.getinfo(test)', pcall(debug.getinfo, test)) print('----- debug.sethook, debug.gethook') f = function(x) g = function(y) return math.min(x, h) end local a = g(x) return a + a end local hook = function(...) print(' ... in hook', ...) local info = debug.getinfo(2, "Sl") if info then print(' info[2]=' .. tostring(info.short_src) .. ',' .. tostring(info.currentline)) end end local tryfunc = function(hook, mask, func, arg) local x, f, h, m pcall(function() debug.sethook(hook, mask) x = func(arg) f, h, m = debug.gethook() end) debug.sethook() return x, f, h, m end local tryhooks = function(mask) local s1, a1, b1, c1, d1 = pcall(tryfunc, hook, mask, f, 333) print('hook = ' .. mask .. ' -> ' .. 'result=' .. tostring(s1) .. ',' .. tostring(a1) .. ',' .. type(b1) .. ',' .. type(c1) .. ',' .. tostring(b1 == f) .. ',' .. tostring(c1 == hook) .. ',' .. tostring(d1) .. ' ') end --[[ tryhooks("c") tryhooks("r") tryhooks("l") tryhooks("crl") --]]
local array = require('containers/array') local map = require('containers/map') local set = require('containers/set') local optionDescription = require('program-options/option-description') local optionsDescription = {} optionsDescription.__index = optionsDescription function optionsDescription.new(caption) checkArg(1, caption, "string", "nil") local self = setmetatable({}, optionsDescription) self._caption = caption or "" self._opts = array.new() -- array<optionDescription> self._groups = array.new() -- array<optionsDescription> self._optMap = map.new() -- map<string, optionDescription> self._hidden = false return self end function optionsDescription.isInstance(obj) checkArg(1, obj, "table") local meta = getmetatable(obj) if meta == optionsDescription then return true elseif meta and type(meta.__index) == "table" then return optionsDescription.isInstance(meta.__index) else return false end end function optionsDescription:add(desc) if optionDescription.isInstance(desc) then if self._optMap:has(desc:longName()) then error("Duplicate option: "..desc:longName(), 2) elseif desc:shortName() and self._optMap:has(desc:shortName()) then error("Duplicate option: "..desc:shortName(), 2) else self._opts:push(desc) if desc:longName() then self._optMap:set(desc:longName(), desc) end if desc:shortName() then self._optMap:set(desc:shortName(), desc) end end elseif optionsDescription.isInstance(desc) then local inters = self._optMap:intersection(desc._optMap) for k, _ in inters:entries() do error("Duplicate option: "..k, 2) end self._groups:push(desc) self._optMap = self._optMap:union(desc._optMap) else error("Not an instance of optionDescription nor optionsDescription: "..tostring(desc), 2) end return self end function optionsDescription:addOptions() local function helper(...) self:add(optionDescription.new(...)) return helper end return helper end -- State that options in this optionsDescription should not be shown -- in usage messages. function optionsDescription:hidden() self._hidden = true return self end function optionsDescription:isHidden() return self._hidden end -- Returns optionDescription or nil. function optionsDescription:find(name) checkArg(1, name, "string") return self._optMap:get(name, nil) end function optionsDescription:caption() return self._caption end function optionsDescription:options() return self._opts end function optionsDescription:groups() return self._groups end -- Returns a set<optionDescription> consisting of all the known -- options. function optionsDescription:allOpts() return self._groups:foldl( function (xs, group) return xs:union(group:allOpts()) end, set.new(self._opts:values())) end return optionsDescription
-- start.lua PX2_SM:CallFile("DataEditor/scripts/functions.lua") PX2_SM:CallFile("DataEditor/scripts/mainframe.lua") PX2_SM:CallFile("DataEditor/scripts/stageview.lua") PX2_SM:CallFile("DataEditor/scripts/menus.lua") PX2_SM:CallFile("DataEditor/scripts/toolbars.lua")
local anim8 = require('libs.anim8') local Shot = {} function Shot:new(world, x, y, a, spriteset, name) name = name or '' local shot = {} setmetatable(shot, self) self.__index = self shot.b = love.physics.newBody(world, x, y, 'dynamic') shot.b:setMass(1) shot.s = love.physics.newCircleShape(3) shot.f = love.physics.newFixture(shot.b, shot.s) shot.f:setUserData(name..'Shot') shot.r = 3 shot.a = a shot.spriteset = love.graphics.newImage('assets/'..spriteset) local g = anim8.newGrid( 64, 64, shot.spriteset:getWidth(), shot.spriteset:getHeight(), 1, 1 ) shot.anim = anim8.newAnimation(g('4-8',1), 0.1) shot.deading = anim8.newAnimation(g('3-1',1), 0.15) Event:subscribe(shot.f, function(event) local infos, a, b = event[4], event[1], event[2] --if neither of obj is the owner of shot and if (infos[1] ~= name and infos[2] ~= name) and --Shots dont target themselves (infos[1] ~= name..'Shot' or infos[2] ~= name..'Shot') then --update animation to exploded shot.anim = shot.deading Timer:after(0.45, function() shot:destroy() end) end end) return shot end function Shot.update(self, dt) self.anim:update(dt) end function Shot.draw(self, tx, ty) tx = (tx or 0) + math.sin(self.a) * 16 ty = (ty or 0) - math.cos(self.a) * 16 local x, y = self.b:getPosition() love.graphics.circle('line', x + tx - math.sin(self.a) * 16, y + ty + math.cos(self.a) * 16, self.r ) self.anim:draw(self.spriteset, x + tx, y + ty, self.a, 0.5, 0.5) end function Shot.destroy(self) if not self.f:isDestroyed() then self.f:destroy() self.b:destroy() self.s:release() self.draw = function() return end self.update = function() return end end end return setmetatable({}, {__call = function(_, ...) return Shot:new(...) end})
object_intangible_vehicle_barc_speeder_pcd = object_intangible_vehicle_shared_barc_speeder_pcd:new { } ObjectTemplates:addTemplate(object_intangible_vehicle_barc_speeder_pcd, "object/intangible/vehicle/barc_speeder_pcd.iff")
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author ([email protected]). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] local Clockwork = Clockwork; local SysTime = SysTime; local IsValid = IsValid; local pairs = pairs; local table = table; local vgui = vgui; local math = math; local PANEL = {}; -- Called when the panel is initialized. function PANEL:Init() if (!Clockwork.theme:Call("PreMainMenuInit", self)) then self:SetSize(ScrW(), ScrH()); self:SetDrawOnTop(false); self:SetPaintBackground(false); self:SetMouseInputEnabled(true); self:SetKeyboardInputEnabled(true); Clockwork.kernel:SetNoticePanel(self); self.CreateTime = SysTime(); self.activePanel = nil; Clockwork.theme:Call("PostMainMenuInit", self); self:Rebuild(); end; end; -- A function to return to the main menu. function PANEL:ReturnToMainMenu(bPerformCheck) if (bPerformCheck) then if (IsValid(self.activePanel) and self.activePanel:IsVisible()) then self.activePanel:MakePopup(); end; return; end; if (CW_CONVAR_FADEPANEL:GetInt() == 1) then if (IsValid(self.activePanel) and self.activePanel:IsVisible()) then self.activePanel:MakePopup(); self:FadeOut(0.5, self.activePanel, function() self.activePanel = nil; end ); end; else self.activePanel:SetVisible(false); self.activePanel = nil; end; self:MoveTo(self.tabX, self.tabY, 0.4, 0, 4); end; -- A function to rebuild the panel. function PANEL:Rebuild(change) if (!Clockwork.theme:Call("PreMainMenuRebuild", self)) then self.tabX = GetConVarNumber("cwTabPosX") or 0; self.tabY = GetConVarNumber("cwTabPosY") or 0; local activePanel = Clockwork.menu:GetActivePanel(); local smallTextFont = Clockwork.option:GetFont("menu_text_small"); local scrW = ScrW(); local scrH = ScrH(); if (IsValid(self.closeMenu)) then self.closeMenu:Remove(); self.characterMenu:Remove(); end; self.closeMenu = Clockwork.kernel:CreateMarkupToolTip(vgui.Create("cwLabelButton", self)); self.closeMenu:SetFont(smallTextFont); self.closeMenu:SetText(L("TabMenuClose")); self.closeMenu:SetCallback(function(button) self:SetOpen(false); end); self.closeMenu:SetTooltip(L("TabMenuCloseDesc")); self.closeMenu:SizeToContents(); self.closeMenu:SetMouseInputEnabled(true); self.closeMenu:SetPos(self.tabX, self.tabY); self.characterMenu = Clockwork.kernel:CreateMarkupToolTip(vgui.Create("cwLabelButton", self)); self.characterMenu:SetFont(smallTextFont); self.characterMenu:SetText(L("TabMenuCharacters")); self.characterMenu:SetCallback(function(button) self:SetOpen(false); Clockwork.character:SetPanelOpen(true); end); self.characterMenu:SetTooltip(L("TabMenuCharactersDesc")); self.characterMenu:SizeToContents(); self.characterMenu:SetMouseInputEnabled(true); self.characterMenu:SetPos(self.closeMenu.x, self.closeMenu.y + self.closeMenu:GetTall() + 8); if (change) then self:SetPos(self.tabX, self.tabY); elseif (IsValid(self.activePanel)) then local width = self.activePanel:GetWide(); self:SetPos(-400, self.tabY); self:MoveTo(ScrW() - width - self.tabX - self.closeMenu:GetWide() * 1.50, self.tabY, 0.4, 0, 4); else self:SetPos(-400, self.tabY); self:MoveTo(self.tabX, self.tabY, 0.4, 0, 4); end; local width = self.characterMenu:GetWide(); local oy = self.characterMenu.y + (self.characterMenu:GetTall() * 3); local ox = self.closeMenu.x; local y = oy; local x = ox; for k, v in pairs(Clockwork.menu:GetItems()) do if (IsValid(v.button)) then v.button:Remove(); end; end; Clockwork.MenuItems.stored = {}; Clockwork.plugin:Call("MenuItemsAdd", Clockwork.MenuItems); Clockwork.plugin:Call("MenuItemsDestroy", Clockwork.MenuItems); table.sort(Clockwork.MenuItems.stored, function(a, b) return a.text < b.text; end); for k, v in pairs(Clockwork.MenuItems.stored) do local button, panel = nil, nil; if (Clockwork.menu.stored[v.panel]) then panel = Clockwork.menu.stored[v.panel].panel; else panel = vgui.Create(v.panel, self); panel:SetVisible(false); panel:SetSize(Clockwork.menu:GetWidth(), panel:GetTall()); panel:SetPos(self.tabX + (scrW - width - (scrW * 0.04)), self.tabY + (scrH * 0.1)); panel.Name = v.text; end; if (!panel.IsButtonVisible or panel:IsButtonVisible()) then button = vgui.Create("cwMenuButton", self); button:NoClipping(true); end; if (button) then button:SetupLabel(v, panel, x, y); button:SetPos(x, y); y = y + button:GetTall(); isVisible = true; if (button:GetWide() > width) then width = button:GetWide(); end; end; Clockwork.menu.stored[v.panel] = { button = button, panel = panel }; end; for k, v in pairs(Clockwork.menu:GetItems()) do if (activePanel == v.panel) then if (!IsValid(v.button)) then if (CW_CONVAR_FADEPANEL:GetInt() == 1) then self:FadeOut(0.5, activePanel, function() self.activePanel = nil; end); else self.activePanel:SetVisible(false); self.activePanel = nil; end; end; end; end; Clockwork.theme:Call("PostMainMenuRebuild", self); end; end; -- A function to open a panel. function PANEL:OpenPanel(panelToOpen) if (!Clockwork.theme:Call("PreMainMenuOpenPanel", self, panelToOpen)) then local width = Clockwork.menu:GetWidth(); local scrW = ScrW(); local scrH = ScrH(); if (IsValid(self.activePanel)) then if (CW_CONVAR_FADEPANEL:GetInt() == 1) then self:FadeOut(0.5, self.activePanel, function() self.activePanel = nil; self:OpenPanel(panelToOpen); end); return; else self.activePanel:SetVisible(false); self.activePanel = nil; self:OpenPanel(panelToOpen); end; end; if (panelToOpen.GetMenuWidth) then width = panelToOpen:GetMenuWidth(); end; self.activePanel = panelToOpen; self.activePanel:SetSize(width, self.activePanel:GetTall()); self.activePanel:MakePopup(); self.activePanel:SetPos(ScrW() + 400, scrH * 0.1); self.activePanel.GetPanelName = function(panel) return panel.Name; end; if (CW_CONVAR_FADEPANEL:GetInt() == 1) then self.activePanel:SetPos(scrW - width - (scrW * 0.04), scrH * 0.1); self.activePanel:SetAlpha(0); self:FadeIn(0.5, self.activePanel, function() timer.Simple(FrameTime() * 0.5, function() if (IsValid(self.activePanel)) then if (self.activePanel.OnSelected) then self.activePanel:OnSelected(); end; end; end); end); else self.activePanel:SetAlpha(255); self.activePanel:SetVisible(true); self.activePanel:MoveTo(scrW - width - (scrW * 0.04), scrH * 0.1, 0.4, 0, 4); end; Clockwork.theme:Call("PostMainMenuOpenPanel", self, panelToOpen); end; end; -- A function to make a panel fade out. function PANEL:FadeOut(speed, panel, Callback) Clockwork.option:PlaySound("rollover"); panel:SetVisible(false); panel:SetAlpha(0); if (Callback) then Callback(); end; end; -- A function to make a panel fade in. function PANEL:FadeIn(speed, panel, Callback) panel:SetVisible(true); panel:SetAlpha(255); if (Callback) then Callback(); end; end; -- Called when the panel is painted. function PANEL:Paint(w, h) if (!Clockwork.theme:Call("PreMainMenuPaint", self)) then derma.SkinHook("Paint", "Panel", self); Clockwork.theme:Call("PostMainMenuPaint", self); end; local x, y = self.tabX - GetConVarNumber("cwBackX"), self.tabY - GetConVarNumber("cwBackY"); local w, h = GetConVarNumber("cwBackW"), GetConVarNumber("cwBackH"); if (CW_CONVAR_SHOWGRADIENT:GetInt() == 1) then Clockwork.kernel:DrawSimpleGradientBox( 0, x, y, w, h, Color(GetConVarNumber("cwBackColorR"), GetConVarNumber("cwBackColorG"), GetConVarNumber("cwBackColorB"), GetConVarNumber("cwBackColorA")) ); elseif (CW_CONVAR_SHOWMATERIAL:GetInt() == 1) then local material = Material(CW_CONVAR_MATERIAL:GetString()); surface.SetDrawColor(GetConVarNumber("cwBackColorR"), GetConVarNumber("cwBackColorG"), GetConVarNumber("cwBackColorB"), GetConVarNumber("cwBackColorA")); surface.SetMaterial(material); surface.DrawTexturedRect(x, y, w, h); end; return true; end; -- Called every fame. function PANEL:Think() if (!Clockwork.theme:Call("PreMainMenuThink", self)) then self:SetVisible(Clockwork.menu:GetOpen()); self:SetSize(ScrW(), ScrH()); self:SetPos(0,0); if (self.tabX != GetConVarNumber("cwTabPosX") or self.tabY != GetConVarNumber("cwTabPosY")) then self.tabX = GetConVarNumber("cwTabPosX"); self.tabY = GetConVarNumber("cwTabPosY"); self:Rebuild(true); end; Clockwork.menu.height = ScrH() * 0.75; Clockwork.menu.width = math.min(ScrW() * 0.7, 768); if (self.fadeOutAnimation) then self.fadeOutAnimation:Run(); end; if (self.fadeInAnimation) then self.fadeInAnimation:Run(); end; Clockwork.theme:Call("PostMainMenuThink", self); local activePanel = Clockwork.menu:GetActivePanel(); local informationColor = Clockwork.option:GetColor("information"); self.closeMenu:OverrideTextColor(informationColor); for k, v in pairs(Clockwork.menu:GetItems()) do if (IsValid(v.button)) then if (v.panel == activePanel) then v.button.LabelButton:OverrideTextColor(informationColor); else v.button.LabelButton:OverrideTextColor(false); end; end; end; end; end; -- A function to set whether the panel is open. function PANEL:SetOpen(bIsOpen) self:SetVisible(bIsOpen); self:ReturnToMainMenu(true); Clockwork.menu.bIsOpen = bIsOpen; gui.EnableScreenClicker(bIsOpen); if (bIsOpen) then self:Rebuild(); self.CreateTime = SysTime(); Clockwork.kernel:SetNoticePanel(self); Clockwork.plugin:Call("MenuOpened"); else Clockwork.plugin:Call("MenuClosed"); end; end; vgui.Register("cwMenu", PANEL, "DPanel"); hook.Add("VGUIMousePressed", "Clockwork.menu:VGUIMousePressed", function(panel, code) local activePanel = Clockwork.menu:GetActivePanel(); local menuPanel = Clockwork.menu:GetPanel(); if (Clockwork.menu:GetOpen() and activePanel and menuPanel == panel) then menuPanel:ReturnToMainMenu(); end; end); Clockwork.datastream:Hook("MenuOpen", function(data) local panel = Clockwork.menu:GetPanel(); if (panel) then Clockwork.menu:SetOpen(data); else Clockwork.menu:Create(data); end; end);
--- The style interpreter. -- @module wonderful.style.interpreter local class = require("lua-objects") local textBuf = require("wonderful.style.buffer") local lexer = require("wonderful.style.lexer") local node = require("wonderful.style.node") local parser = require("wonderful.style.parser") local property = require("wonderful.style.property") local sels = require("wonderful.style.selector") local wtype = require("wonderful.style.type") local tblUtil = require("wonderful.util.table") -- Prevent import loop local style = function() return require("wonderful.style") end local isin = tblUtil.isin local function traverseSpec(spec, func) local function _traverse(target) func(target) if target.ascendant then _traverse(target.ascendant) end if target.parent then _traverse(target.parent) end if target.above then _traverse(target.above) end if target.dirAbove then _traverse(target.dirAbove) end end for k, v in pairs(spec.targets) do _traverse(v) end end local Variable = class(nil, {name = "wonderful.style.interpreter.Variable"}) function Variable:__new__(name, value, public, custom) self.name = name self.value = value self.public = public self.custom = custom end local Rule = class(nil, {name = "wonderful.style.interpreter.Rule"}) function Rule:__new__(priority, spec, properties, line, col, public) self.priority = priority self.spec = spec self.props = properties self.public = public self.line = line self.col = col end function Rule:matches(component) return self.spec:matches(component) end function Rule:getSpecificity() local classSpec, selSpec = 0, 0, 0 traverseSpec(self.spec, function(target) classSpec = classSpec + #target.classes selSpec = selSpec + #target.selectors end) return classSpec, selSpec end local TypeRef = class(nil, {name = "wonderful.style.interpreter.TypeRef"}) function TypeRef:__new__(name, public) self.name = name self.public = public end local Type = class(nil, {name = "wonderful.style.interpreter.Type"}) function Type:__new__(clazz, custom) self.class = clazz self.custom = custom end function Type:matches(instance) return instance:isa(self.class) end function Type:clone() return Type(self.class, self.custom) end local NamedType = class(Type, {name = "wonderful.style.interpreter.NamedType"}) function NamedType:__new__(name, custom) self.name = name self.custom = custom end function NamedType:matches(instance) return instance.NAME == self.name end local AnyType = class(Type, {name = "wonderful.style.interpreter.AnyType"}) function AnyType:__new__(custom) self.custom = custom end function AnyType:matches() return true end local Spec = class(nil, {name = "wonderful.style.interpreter.Spec"}) function Spec:__new__(targets) self.targets = targets end function Spec:matches(component) for _, target in pairs(self.targets) do if self:targetMatches(target, component) then return true end end end function Spec:targetMatches(target, component) -- Check type if target.type then if not target.type:matches(component) then return false end end -- Check classes for k, v in pairs(target.classes) do local classes = component:get("classes") if not classes or not classes:isSet(v) then return false end end -- Check selectors for k, v in pairs(target.selectors) do if not v:matches(component) then return false end end -- Check ascendants if target.ascendant then local ascendant = component while true do ascendant = ascendant.parent if not ascendant then return false end if self:targetMatches(target.ascendant, ascendant) then break end end end -- Check parent if target.parent then if not component.parent then return false end if not self:targetMatches(target.parent, component.parent) then return false end end -- Check siblings above if target.above then local parent = component.parent if not parent then return false end for i, v in ipairs(parent.children) do if v == component then return false end if self:targetMatches(target.above, v) then break end end end -- Check direct sibling above if target.dirAbove then local parent = component.parent if not parent then return false end local _, pos = isin(component, parent.children) if pos == 1 then return false end if not self:targetMatches(target.dirAbove, parent.children[pos - 1]) then return false end end return true end -- TODO: sane error handling! local Context = class(nil, {name = "wonderful.style.interpreter.Context"}) function Context:__new__(args) self.importPriority = 1 self.vars = {} self.rules = {} self.types = {} self.selectors = {} self.properties = {} if args then self.ast = args.parser.ast if args.vars then self:addVars(args.vars, true) end if args.selectors then self:addSelectors(args.selectors, true) end if args.properties then self:addProperties(args.properties, true) end if args.types then self:addTypes(args.types, true) end end end function Context:addVars(vars, custom) for name, value in pairs(vars) do if type(name) ~= "string" or #name == 0 then error("Variable name must be a non-empty string") end if type(value) ~= "table" then value = {value} end self.vars[name] = Variable(name, value, true, custom) end end function Context:addSelectors(selectors, custom) for name, selector in pairs(selectors) do self.selectors[name] = {selector = selector, custom = custom} end end function Context:addProperties(properties, custom) for k, property in pairs(properties) do self.properties[property.name] = {property = property, custom = custom} end end function Context:addTypes(types) for name, type_ in pairs(types) do assert(type(name) == "string", "Type name " .. tostring(name) .. " must be a string") if not type_:isa(Type) then type_ = Type(type_) else type_ = type_:clone() end type_.custom = true self.types[name] = type_ end end function Context:getCustomVars() local result = {} for k, v in pairs(self.vars) do if v.custom then result[k] = v.value end end end function Context:getCustomSels() local result = {} for k, v in pairs(self.selectors) do if v.custom then result[k] = v.value end end end function Context:getCustomProps() local result = {} for k, v in pairs(self.properties) do if v.custom then result[k] = v.value end end end function Context:getCustomTypes() local result = {} for k, v in pairs(self.types) do if v.custom then result[k] = v.class end end end function Context:interpret() if not self.ast then error("The AST has not been set") end for _, stmt in ipairs(self.ast.value) do if stmt:isa(node.ImportNode) then self:import(stmt) elseif stmt:isa(node.VarNode) then self:setVar(stmt) elseif stmt:isa(node.TypeAliasNode) then self:setType(stmt) elseif stmt:isa(node.RuleNode) then self:addRule(stmt) end end self:resolveTypeRefs() self:evalVars() self:processRules() end function Context:import(stmt) if stmt.value:isa(node.PathNode) then -- import "path.wsf"; local file = self:tryOpenFile(stmt.value.value) local buf = textBuf.Buffer(file) local tokStream = lexer.TokenStream(buf) local parser = parser.Parser(tokStream) local ctx = Context({ parser = parser, vars = self:getCustomVars(), selectors = self:getCustomSels(), properties = self:getCustomProps(), types = self:getCustomTypes() }) ctx:interpret() self:merge(ctx) elseif stmt.value:isa(node.NameNode) or stmt.value:isa(node.TypeRefNode) then -- import <module:name>; -- import @Type; local ref = TypeRef(stmt.value) local ctx = self:resolveType(ref).class if ctx:isa(style().Style) then if ctx:isContextStripped() then error("Imported style has its context stripped and can't be imported.") end ctx = ctx.context end if not ctx:isa(Context) then error("Imported name must be a wonderful.style.interpreter:Context") end self:merge(ctx) end end function Context:tryOpenFile(path) -- TODO: it's a good idea to use fs.exists before io.opening local f, reason = io.open(path) if not f then error("Could not open the file at " .. path .. ": " .. reason) end return f end function Context:merge(ctx) for k, v in pairs(ctx.vars) do if v.public and not v.custom then v.priority = self.importPriority self.vars[k] = v end end for k, v in pairs(ctx.types) do if v.public and not v.custom then self.types[k] = v end end local huge = false local priority = 0 for k, v in pairs(ctx.rules) do if v.priority == math.huge then huge = true else priority = math.max(priority, v.priority) end end priority = self.importPriority + priority for k, v in pairs(ctx.rules) do if v.public then local p = v.priority if p == math.huge then p = priority else p = v.priority + self.importPriority - 1 end table.insert(self.rules, Rule(priority, v.spec, v.props, v.line, v.col, true)) end end self.importPriority = self.importPriority + priority + (huge and 1 or 0) + 1 end function Context:setType(stmt) self.types[stmt.name] = TypeRef(stmt.type, stmt.public) end function Context:setVar(stmt) self.vars[stmt.name] = Variable(stmt.name, stmt.value, stmt.public) end function Context:addRule(stmt) local props = {} for k, v in ipairs(stmt.properties) do props[v.name] = v end local spec = Spec(stmt.targets) traverseSpec(spec, function(target) if target.type then target.type = TypeRef(target.type) end end) table.insert(self.rules, Rule(math.huge, spec, props, stmt.line, stmt.col, stmt.public)) end function Context:resolveTypeRefs() for k, v in pairs(self.types) do self.types[k] = self:resolveType(self.types[k]) end -- Now find any references for k, v in pairs(self.vars) do if v.type then v.type = self:resolveType(v.type) end end for _, rule in pairs(self.rules) do traverseSpec(rule.spec, function(target) if target.type then target.type = self:resolveType(target.type) end end) end end -- Resolves TypeRef to Type function Context:resolveType(typeRef) if typeRef:isa(Type) then return typeRef end local name = typeRef.name if name:isa(node.TypeRefNode) then local referenced = self.types[name.value] if not referenced then error("Type @" .. name.value .. " is undefined") end self.types[name.value] = self:resolveType(referenced) return self.types[name.value] elseif name:isa(node.NameNode) then if name.module then return self:importName(name.path, name.name) else return self:loadName(name.path, name.name) end elseif name:isa(node.ClassNameNode) then return NamedType(name.value, false) elseif name:isa(node.AnyTypeNode) then return AnyType(false) end end function Context:processRules() for _, rule in pairs(self.rules) do -- Selectors traverseSpec(rule.spec, function(target) for k, selNode in pairs(target.selectors) do -- check if the selector's been already processed if selNode:isa(node.SelectorNode) then local selector = self.selectors[selNode.name] if not selector or selector.custom ~= selNode.custom then error("Unknown selector: " .. (selNode.custom and "~" or "") .. selNode.name) end target.selectors[k] = selector.selector(selNode.value) end end end) -- Properties for k, v in pairs(rule.props) do -- check if the property's been already processed if v:isa(node.PropertyNode) then local prop = self.properties[v.name] if not prop or prop.custom ~= v.custom then error("Unknown property: " .. (v.custom and "~" or "") .. v.name) end rule.props[k] = prop.property(v.value) end end -- Classes traverseSpec(rule.spec, function(target) for k, v in pairs(target.classes) do if type(v) ~= "string" then target.classes[k] = v.value end end end) end end function Context:evalVars() for _, rule in pairs(self.rules) do for _, prop in pairs(rule.props) do if prop:isa(node.PropertyNode) then local value = prop.value for i = #value, 1, -1 do local token = value[i] if type(token) == "table" and token.isa and token:isa(lexer.VarRefToken) then local var = self.vars[token.value] if not var then error("Variable $" .. token.value .. " is not defined") end table.remove(value, i) for j = #var.value, 1, -1 do table.insert(value, i, var.value[j]) end end end end end end end function Context:importName(modPath, name) -- TODO: error handling! return require(modPath)[name] end function Context:loadName(path, name) -- TODO: error handling! return load(path, "t", _G)()[name] end return { Variable = Variable, Rule = Rule, TypeRef = TypeRef, Type = Type, NamedType = NamedType, AnyType = AnyType, Spec = Spec, Context = Context, }
---------------------------------------- -- -- Copyright (c) 2015, Hadriel Kaplan -- -- author: Hadriel Kaplan <[email protected]> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['pcapng_test_gen'] then return end local block = require "blocks" local input = require "input" local test = { category = 'difficult', description = "ISBs with various options, in different SHB sections", } local timestamp = UInt64(0x64ca47aa, 0x0004c397) function test:compile() local idb0 = block.IDB(0, input.linktype.ETHERNET, 96, "eth0") local idb1 = block.IDB(1, input.linktype.NULL, 0, "null1") -- will be in new section, so ID=0 local idb2 = block.IDB(0, input.linktype.ETHERNET, 128, "silly ethernet interface 2") self.blocks = { block.SHB("Apple MBP", "OS-X 10.10.5", "pcap_writer.lua") :addOption('comment', self.testname .. " SHB-0"), idb0, idb1, block.EPB( idb0, input:getData(1, 96), timestamp ), block.ISB(idb1, timestamp), ---- new SHB section ---- block.SHB("Apple MBP", "OS-X 10.10.5", "pcap_writer.lua") :addOption('UNKNOWN_SPEC') :addOption('UNKNOWN_LOCAL', self.testname .. " NRB") :addOption('comment', self.testname .. " SHB-1"), idb2, block.EPB( idb2, input:getData(2, 128), timestamp ), block.ISB(idb2, timestamp + 1000) :addOption( block.OptionFormat ('isb_starttime', "I4 I4", { timestamp:higher(), timestamp:lower() }) ) :addOption( block.OptionFormat ('isb_endtime', "I4 I4", { timestamp:higher(), (timestamp + 1000):lower() }) ) :addOption( block.OptionFormat ('isb_filteraccept', "E", UInt64(42)) ) :addOption( block.OptionFormat ('isb_ifdrop', "E", UInt64(10)) ) :addOption('UNKNOWN_SPEC') :addOption('UNKNOWN_LOCAL', self.testname .. " NRB") :addOption('comment', self.testname .. " ISB-2"), block.SPB( input:getData(3, 128) ), ---- new SHB section ---- block.SHB("Apple MBP", "OS-X 10.10.5", "pcap_writer.lua") :addOption('comment', self.testname .. " SHB-2"), idb0, idb1, block.ISB(idb0) :addOption( block.OptionFormat ('isb_starttime', "I4 I4", { timestamp:higher(), timestamp:lower() }) ) :addOption( block.OptionFormat ('isb_endtime', "I4 I4", { timestamp:higher(), (timestamp + 1000):lower() }) ) :addOption( block.OptionFormat ('isb_ifrecv', "E", UInt64(100)) ) :addOption( block.OptionFormat ('isb_ifdrop', "E", UInt64(1)) ) :addOption( block.OptionFormat ('isb_filteraccept', "E", UInt64(9)) ) :addOption( block.OptionFormat ('isb_osdrop', "E", UInt64(42)) ) :addOption( block.OptionFormat ('isb_usrdeliv', "E", UInt64(6)) ) :addOption('comment', self.testname .. " ISB-0"), block.EPB( idb1, input:getData(5), timestamp + 3000 ), block.ISB(idb0), } end return test
object_tangible_furniture_all_event_flag_game_neut_banner = object_tangible_furniture_all_shared_event_flag_game_neut_banner:new { } ObjectTemplates:addTemplate(object_tangible_furniture_all_event_flag_game_neut_banner, "object/tangible/furniture/all/event_flag_game_neut_banner.iff")
--- Functions -- @section local _ITEMS = {} local Dyn = require 'ta.dynamo' local Env = require 'ta.item_env' local ip = require 'solstice.itemprop' local ipc = ip.const local Cre = require 'solstice.creature' local env_mt = { __index = table.chain(M.env, ipc) } --- Load item file. -- @param file Item file to load. function M.Load(file) E.item = setmetatable({}, env_mt) local res = runfile(file, E.item) _ITEMS[assert(res.resref)] = res E.item = nil end --- Generate item -- @param object Object to create item on. -- @param resref Resref of item to create. -- @param[opt=false] max If true, the maximum value of an -- item property parameter. -- @see solstice.item.Load function M.Generate(object, resref, max) local item = _ITEMS[resref] if not item then error("No such resref: " .. resref) end local it = object:GiveItem(resref) if not it:GetIsValid() then error("Invalid item: Resref: " .. resref) end -- This probably could be done in a better fashion... if item.value then it:SetGoldValue(item.value) end for _, p in ipairs(item.properties) do local f = p.f if not f then error "No item property function!" end local t = {} for _, v in ipairs(p) do local val = Dyn.GetValue(v, max) table.insert(t, val) end local count = p.n or 1 for i = 1,count do if not p.chance or math.random(1, 100) <= p.chance then it:AddItemProperty(Eff.DURATION_PERMANENT, ip[f](unpack(t))) end end end end
--- --- @author Dylan MALANDAIN, Kalyptus --- @version 1.0.0 --- created at [24/05/2021 10:02] --- local ItemsSettings = { CheckBox = { Textures = { "shop_box_blankb", -- 1 "shop_box_tickb", -- 2 "shop_box_blank", -- 3 "shop_box_tick", -- 4 "shop_box_crossb", -- 5 "shop_box_cross", -- 6 }, X = 380, Y = -6, Width = 50, Height = 50 }, Rectangle = { Y = 0, Width = 431, Height = 38 } } local function StyleCheckBox(Selected, Checked, Box, BoxSelect, OffSet) local CurrentMenu = RageUI.CurrentMenu; if OffSet == nil then OffSet = 0 end if Selected then if Checked then Graphics.Sprite("commonmenu", ItemsSettings.CheckBox.Textures[Box], CurrentMenu.X + 380 + CurrentMenu.WidthOffset - OffSet, CurrentMenu.Y + -6 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 50, 50) else Graphics.Sprite("commonmenu", ItemsSettings.CheckBox.Textures[1], CurrentMenu.X + 380 + CurrentMenu.WidthOffset - OffSet, CurrentMenu.Y + -6 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 50, 50) end else if Checked then Graphics.Sprite("commonmenu", ItemsSettings.CheckBox.Textures[BoxSelect], CurrentMenu.X + 380 + CurrentMenu.WidthOffset - OffSet, CurrentMenu.Y + -6 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 50, 50) else Graphics.Sprite("commonmenu", ItemsSettings.CheckBox.Textures[3], CurrentMenu.X + 380 + CurrentMenu.WidthOffset - OffSet, CurrentMenu.Y + -6 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 50, 50) end end end ---@class Items Items = {} ---AddButton --- --- Add items button. --- ---@param Label string ---@param Description string ---@param Style table ---@param Actions fun(onSelected:boolean, onActive:boolean) ---@param Submenu any ---@public ---@return void function Items:AddButton(Label, Description, Style, Actions, Submenu) local CurrentMenu = RageUI.CurrentMenu local Option = RageUI.Options + 1 if CurrentMenu.Pagination.Minimum <= Option and CurrentMenu.Pagination.Maximum >= Option then local Active = CurrentMenu.Index == Option RageUI.ItemsSafeZone(CurrentMenu) local haveLeftBadge = Style.LeftBadge and Style.LeftBadge ~= RageUI.BadgeStyle.None local haveRightBadge = (Style.RightBadge and Style.RightBadge ~= RageUI.BadgeStyle.None) local LeftBadgeOffset = haveLeftBadge and 27 or 0 local RightBadgeOffset = haveRightBadge and 32 or 0 if Style.Color and Style.Color.BackgroundColor then Graphics.Rectangle(CurrentMenu.X, CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + CurrentMenu.WidthOffset, 38, Style.Color.BackgroundColor[1], Style.Color.BackgroundColor[2], Style.Color.BackgroundColor[3], Style.Color.BackgroundColor[4]) end if Active then if Style.Color and Style.Color.HightLightColor then Graphics.Rectangle(CurrentMenu.X, CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + CurrentMenu.WidthOffset, 38, Style.Color.HightLightColor[1], Style.Color.HightLightColor[2], Style.Color.HightLightColor[3], Style.Color.HightLightColor[4]) else Graphics.Sprite("commonmenu", "gradient_nav", CurrentMenu.X, CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + CurrentMenu.WidthOffset, 38) end end if not (Style.IsDisabled) then if haveLeftBadge then if (Style.LeftBadge ~= nil) then local LeftBadge = Style.LeftBadge(Active) Graphics.Sprite(LeftBadge.BadgeDictionary or "commonmenu", LeftBadge.BadgeTexture or "", CurrentMenu.X, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, LeftBadge.BadgeColour and LeftBadge.BadgeColour.R or 255, LeftBadge.BadgeColour and LeftBadge.BadgeColour.G or 255, LeftBadge.BadgeColour and LeftBadge.BadgeColour.B or 255, LeftBadge.BadgeColour and LeftBadge.BadgeColour.A or 255) end end if haveRightBadge then if (Style.RightBadge ~= nil) then local RightBadge = Style.RightBadge(Active) Graphics.Sprite(RightBadge.BadgeDictionary or "commonmenu", RightBadge.BadgeTexture or "", CurrentMenu.X + 385 + CurrentMenu.WidthOffset, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, RightBadge.BadgeColour and RightBadge.BadgeColour.R or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.G or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.B or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.A or 255) end end if Style.RightLabel then Graphics.Text(Style.RightLabel, CurrentMenu.X + 420 - RightBadgeOffset + CurrentMenu.WidthOffset, CurrentMenu.Y + 4 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, Active and 0 or 245, Active and 0 or 245, Active and 0 or 245, 255, 2) end Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, Active and 0 or 245, Active and 0 or 245, Active and 0 or 245, 255) else local RightBadge = RageUI.BadgeStyle.Lock(Active) Graphics.Sprite(RightBadge.BadgeDictionary or "commonmenu", RightBadge.BadgeTexture or "", CurrentMenu.X + 385 + CurrentMenu.WidthOffset, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, RightBadge.BadgeColour and RightBadge.BadgeColour.R or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.G or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.B or 255, RightBadge.BadgeColour and RightBadge.BadgeColour.A or 255) Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 163, 159, 148, 255) end RageUI.ItemOffset = RageUI.ItemOffset + 38 if (Active) then RageUI.ItemsDescription(Description); if not (Style.IsDisabled) then local Selected = (CurrentMenu.Controls.Select.Active) Actions(Selected) if Selected then Audio.PlaySound(RageUI.Settings.Audio.Select.audioName, RageUI.Settings.Audio.Select.audioRef) if Submenu and Submenu() then RageUI.NextMenu = Submenu end end end end end RageUI.Options = RageUI.Options + 1 end ---CheckBox ---@param Label string ---@param Description string ---@param Checked boolean ---@param Style table ---@param Actions fun(onSelected:boolean, IsChecked:boolean) function Items:CheckBox(Label, Description, Checked, Style, Actions) local CurrentMenu = RageUI.CurrentMenu; local Option = RageUI.Options + 1 if CurrentMenu.Pagination.Minimum <= Option and CurrentMenu.Pagination.Maximum >= Option then local Active = CurrentMenu.Index == Option; local Selected = false; local LeftBadgeOffset = ((Style.LeftBadge == RageUI.BadgeStyle.None or Style.LeftBadge == nil) and 0 or 27) local RightBadgeOffset = ((Style.RightBadge == RageUI.BadgeStyle.None or Style.RightBadge == nil) and 0 or 32) local BoxOffset = 0 RageUI.ItemsSafeZone(CurrentMenu) if (Active) then Graphics.Sprite("commonmenu", "gradient_nav", CurrentMenu.X, CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + CurrentMenu.WidthOffset, 38) end if (Style.IsDisabled == nil) or not (Style.IsDisabled) then if Active then Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 0, 0, 0, 255) else Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 245, 245, 245, 255) end if Style.LeftBadge ~= nil then if Style.LeftBadge ~= RageUI.BadgeStyle.None then local BadgeData = Style.LeftBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour and BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.A or 255) end end if Style.RightBadge ~= nil then if Style.RightBadge ~= RageUI.BadgeStyle.None then local BadgeData = Style.RightBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X + 385 + CurrentMenu.WidthOffset, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour and BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.A or 255) end end else local LeftBadge = RageUI.BadgeStyle.Lock LeftBadgeOffset = ((LeftBadge == RageUI.BadgeStyle.None or LeftBadge == nil) and 0 or 27) if Active then Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 0, 0, 0, 255) else Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 163, 159, 148, 255) end if LeftBadge ~= RageUI.BadgeStyle.None and LeftBadge ~= nil then local BadgeData = LeftBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour.A or 255) end end if (Active) then if Style.RightLabel ~= nil and Style.RightLabel ~= "" then Graphics.Text(Style.RightLabel, CurrentMenu.X + 420 - RightBadgeOffset + CurrentMenu.WidthOffset, CurrentMenu.Y + 4 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 0, 0, 0, 255, 2) BoxOffset = MeasureStringWidth(Style.RightLabel, 0, 0.35) end else if Style.RightLabel ~= nil and Style.RightLabel ~= "" then Graphics.Text(Style.RightLabel, CurrentMenu.X + 420 - RightBadgeOffset + CurrentMenu.WidthOffset, CurrentMenu.Y + 4 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 245, 245, 245, 255, 2) BoxOffset = MeasureStringWidth(Style.RightLabel, 0, 0.35) end end BoxOffset = RightBadgeOffset + BoxOffset if Style.Style ~= nil then if Style.Style == 1 then StyleCheckBox(Active, Checked, 2, 4, BoxOffset) elseif Style.Style == 2 then StyleCheckBox(Active, Checked, 5, 6, BoxOffset) else StyleCheckBox(Active, Checked, 2, 4, BoxOffset) end else StyleCheckBox(Active, Checked, 2, 4, BoxOffset) end if (Active) and (CurrentMenu.Controls.Select.Active) then Selected = true; Checked = not Checked Audio.PlaySound(RageUI.Settings.Audio.Select.audioName, RageUI.Settings.Audio.Select.audioRef) end if (Active) then Actions(Selected, Checked) RageUI.ItemsDescription(Description) end RageUI.ItemOffset = RageUI.ItemOffset + 38 end RageUI.Options = RageUI.Options + 1 end ---AddSeparator --- --- Add separator --- ---@param Label string ---@public ---@return void function Items:AddSeparator(Label) local CurrentMenu = RageUI.CurrentMenu local Option = RageUI.Options + 1 if CurrentMenu.Pagination.Minimum <= Option and CurrentMenu.Pagination.Maximum >= Option then local Active = CurrentMenu.Index == Option; if (Label ~= nil) then Graphics.Text(Label, CurrentMenu.X + 0 + (CurrentMenu.WidthOffset * 2.5 ~= 0 and CurrentMenu.WidthOffset * 2.5 or 200), CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 245, 245, 245, 255, 1) end RageUI.ItemOffset = RageUI.ItemOffset + 38 if (Active) then if (RageUI.LastControl) then CurrentMenu.Index = Option - 1 if (CurrentMenu.Index < 1) then CurrentMenu.Index = RageUI.CurrentMenu.Options end else CurrentMenu.Index = Option + 1 end RageUI.ItemsDescription(nil) end end RageUI.Options = RageUI.Options + 1 end ---AddList ---@param Label string ---@param Items table<any, any> ---@param Index number ---@param Style table<any, any> ---@param Description string ---@param Actions fun(Index:number, onSelected:boolean, onListChange:boolean)) ---@param Submenu any function Items:AddList(Label, Items, Index, Description, Style, Actions, Submenu) local CurrentMenu = RageUI.CurrentMenu; local Option = RageUI.Options + 1 if CurrentMenu.Pagination.Minimum <= Option and CurrentMenu.Pagination.Maximum >= Option then local Active = CurrentMenu.Index == Option; local onListChange = false; RageUI.ItemsSafeZone(CurrentMenu) local LeftBadgeOffset = ((Style.LeftBadge == RageUI.BadgeStyle.None or Style.LeftBadge == nil) and 0 or 27) local RightBadgeOffset = ((Style.RightBadge == RageUI.BadgeStyle.None or Style.RightBadge == nil) and 0 or 32) local RightOffset = 0 local ListText = (type(Items[Index]) == "table") and string.format("← %s →", Items[Index].Name) or string.format("← %s →", Items[Index]) or "NIL" if (Active) then Graphics.Sprite("commonmenu", "gradient_nav", CurrentMenu.X, CurrentMenu.Y + 0 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + CurrentMenu.WidthOffset, 38) end if (not Style.IsDisabled) then if Active then if Style.RightLabel ~= nil and Style.RightLabel ~= "" then Graphics.Text(Style.RightLabel, CurrentMenu.X + 420 - RightBadgeOffset + CurrentMenu.WidthOffset, CurrentMenu.Y + 4 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 0, 0, 0, 255, 2) RightOffset = Graphics.MeasureStringWidth(Style.RightLabel, 0, 0.35) end else if Style.RightLabel ~= nil and Style.RightLabel ~= "" then RightOffset = Graphics.MeasureStringWidth(Style.RightLabel, 0, 0.35) Graphics.Text(Style.RightLabel, CurrentMenu.X + 420 - RightBadgeOffset + CurrentMenu.WidthOffset, CurrentMenu.Y + 4 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 245, 245, 245, 255, 2) end end end RightOffset = RightBadgeOffset * 1.3 + RightOffset if (not Style.IsDisabled) then if (Active) then Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 0, 0, 0, 255) Graphics.Text(ListText, CurrentMenu.X + 403 + 15 + CurrentMenu.WidthOffset - RightOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 0, 0, 0, 255, 2) else Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 245, 245, 245, 255) Graphics.Text(ListText, CurrentMenu.X + 403 + 15 + CurrentMenu.WidthOffset - RightOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 245, 245, 245, 255, 2) end else Graphics.Text(Label, CurrentMenu.X + 8 + LeftBadgeOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.33, 163, 159, 148, 255) Graphics.Text(ListText, CurrentMenu.X + 403 + 15 + CurrentMenu.WidthOffset, CurrentMenu.Y + 3 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 0, 0.35, 163, 159, 148, 255, 2) end if type(Style) == "table" then if Style.Enabled == true or Style.Enabled == nil then if type(Style) == 'table' then if Style.LeftBadge ~= nil then if Style.LeftBadge ~= RageUI.BadgeStyle.None then local BadgeData = Style.LeftBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour and BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.A or 255) end end if Style.RightBadge ~= nil then if Style.RightBadge ~= RageUI.BadgeStyle.None then local BadgeData = Style.RightBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X + 385 + CurrentMenu.WidthOffset, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour and BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour and BadgeData.BadgeColour.A or 255) end end end else local LeftBadge = RageUI.BadgeStyle.Lock if LeftBadge ~= RageUI.BadgeStyle.None and LeftBadge ~= nil then local BadgeData = LeftBadge(Active) Graphics.Sprite(BadgeData.BadgeDictionary or "commonmenu", BadgeData.BadgeTexture or "", CurrentMenu.X, CurrentMenu.Y + -2 + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 40, 40, 0, BadgeData.BadgeColour.R or 255, BadgeData.BadgeColour.G or 255, BadgeData.BadgeColour.B or 255, BadgeData.BadgeColour.A or 255) end end else error("UICheckBox Style is not a `table`") end RageUI.ItemOffset = RageUI.ItemOffset + 38 if (Active) then RageUI.ItemsDescription(Description); if (not Style.IsDisabled) then if (CurrentMenu.Controls.Left.Active) and not (CurrentMenu.Controls.Right.Active) then Index = Index - 1 if Index < 1 then Index = #Items end onListChange = true Audio.PlaySound(RageUI.Settings.Audio.LeftRight.audioName, RageUI.Settings.Audio.LeftRight.audioRef) elseif (CurrentMenu.Controls.Right.Active) and not (CurrentMenu.Controls.Left.Active) then Index = Index + 1 if Index > #Items then Index = 1 end onListChange = true Audio.PlaySound(RageUI.Settings.Audio.LeftRight.audioName, RageUI.Settings.Audio.LeftRight.audioRef) end local Selected = (CurrentMenu.Controls.Select.Active) Actions(Index, Selected, onListChange, Active) if (Selected) then Audio.PlaySound(RageUI.Settings.Audio.Select.audioName, RageUI.Settings.Audio.Select.audioRef) if Submenu ~= nil and type(Submenu) == "table" then RageUI.NextMenu = Submenu[Index] end end end end end RageUI.Options = RageUI.Options + 1 end ---Heritage ---@param Mum number ---@param Dad number function Items:Heritage(Mum, Dad) local CurrentMenu = RageUI.CurrentMenu; if Mum < 0 or Mum > 21 then Mum = 0 end if Dad < 0 or Dad > 23 then Dad = 0 end if Mum == 21 then Mum = "special_female_" .. (tonumber(string.sub(Mum, 2, 2)) - 1) else Mum = "female_" .. Mum end if Dad >= 21 then Dad = "special_male_" .. (tonumber(string.sub(Dad, 2, 2)) - 1) else Dad = "male_" .. Dad end Graphics.Sprite("pause_menu_pages_char_mom_dad", "mumdadbg", CurrentMenu.X, CurrentMenu.Y + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 431 + (CurrentMenu.WidthOffset / 1), 228) Graphics.Sprite("char_creator_portraits", Dad, CurrentMenu.X + 195 + (CurrentMenu.WidthOffset / 2), CurrentMenu.Y + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 228, 228) Graphics.Sprite("char_creator_portraits", Mum, CurrentMenu.X + 25 + (CurrentMenu.WidthOffset / 2), CurrentMenu.Y + CurrentMenu.SubtitleHeight + RageUI.ItemOffset, 228, 228) RageUI.ItemOffset = RageUI.ItemOffset + 228 end
function firstToUpper(str) return (str:gsub("^%l", string.upper)) end local main = {} print("Loading Feature Lib") main.menu, a = loadsubmodule("featurelib", "menu") main.menu.init() main.items = {} main.registeritem = function (item_name, script_name) item_name_l = item_name:lower() script_name = tostring(script_name) --Item reg local first = false if(not main.items[item_name_l])then main.items[item_name_l] = {} first = true end if(main.items[item_name_l][script_name])then error("[Feature lib] Adding items twice is not allowed") end main.items[item_name_l][script_name] = first --Menu if(first)then main.menu.m:menu(item_name_l, firstToUpper(item_name_l)) end main.menu.m[item_name_l]:boolean(script_name, script_name, first) print("[Feature lib] Added " .. script_name .. " as item handler for " .. item_name_l .. " | Activated: " .. tostring(first)) end main.caniuse = function(item_name, script_name) item_name_l = item_name:lower() script_name = tostring(script_name) if(not main.items[item_name_l])then print("[Feature lib] " ..item_name_l .. " is not registered [Callee: " .. script_name .. "]") return false end return main.items[item_name_l][script_name] end return main
local logger = require 'rspamd_logger' rspamd_config:register_symbol({ name = 'ANY_A', score = -1.0, group = "any", callback = function() return true, 'hello3' end }) rspamd_config:add_condition('ANY_A', function(task) logger.infox(task, 'hello from condition1') task:insert_result('ANY_A', 1.0, 'hello1') return true end) rspamd_config:add_condition('ANY_A', function(task) logger.infox(task, 'hello from condition2') task:insert_result('ANY_A', 1.0, 'hello2') return true end)
--==================================================================================== -- #Author: Jonathan D @Gannon --==================================================================================== --==================================================================================== -- --==================================================================================== --==================================================================================== -- Utils --==================================================================================== function getPhoneRandomNumber() local base = math.random(1,3) if base <= 2 then return '0' .. math.random(600000000,699999999) else return '0' .. math.random(700000000,799999999) end end function getSourceFromIdentifier(identifier, cb) TriggerEvent("es:getPlayers", function(users) for k , user in pairs(users) do if user.get("identifier") == identifier then cb(k) return end end end) cb(nil) end function getNumberPhone(identifier) local result = MySQL.Sync.fetchAll("SELECT users.phone_number FROM users WHERE users.identifier = @identifier", { ['@identifier'] = identifier }) if result[1] ~= nil then return result[1].phone_number end return nil end function getIdentifierByPhoneNumber(phone_number) local result = MySQL.Sync.fetchAll("SELECT users.identifier FROM users WHERE users.phone_number = @phone_number", { ['@phone_number'] = phone_number }) if result[1] ~= nil then return result[1].identifier end return nil end --==================================================================================== -- Contacts --==================================================================================== function getContacts(identifier) local result = MySQL.Sync.fetchAll("SELECT phone_users_contacts.id, phone_users_contacts.number, phone_users_contacts.display FROM phone_users_contacts WHERE phone_users_contacts.identifier = @identifier", { ['@identifier'] = identifier }) return result end function addContact(source, identifier, number, display) local sourcePlayer = tonumber(source) print(number .. ' ' .. display) MySQL.Sync.execute("INSERT INTO phone_users_contacts (`identifier`, `number`,`display`) VALUES(@identifier, @number, @display)", { ['@identifier'] = identifier, ['@number'] = number, ['@display'] = display, }) notifyContactChange(sourcePlayer, identifier) end function updateContact(source, identifier, id, number, display) local sourcePlayer = tonumber(source) MySQL.Sync.execute("UPDATE phone_users_contacts SET number = @number, display = @display WHERE id = @id", { ['@number'] = number, ['@display'] = display, ['@id'] = id, }) notifyContactChange(sourcePlayer, identifier) end function deleteContact(source, identifier, id) local sourcePlayer = tonumber(source) MySQL.Sync.execute("DELETE FROM phone_users_contacts WHERE `identifier` = @identifier AND `id` = @id", { ['@identifier'] = identifier, ['@id'] = id, }) notifyContactChange(sourcePlayer, identifier) end function deleteAllContact(identifier) MySQL.Sync.execute("DELETE FROM phone_users_contacts WHERE `identifier` = @identifier", { ['@identifier'] = identifier }) end function notifyContactChange(source, identifier) local sourcePlayer = tonumber(source) if sourcePlayer ~= nil then TriggerClientEvent("gcPhone:contactList", sourcePlayer, getContacts(identifier)) end end RegisterServerEvent('gcPhone:addContact') AddEventHandler('gcPhone:addContact', function(display, phoneNumber) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] addContact(sourcePlayer, identifier, phoneNumber, display) end) RegisterServerEvent('gcPhone:updateContact') AddEventHandler('gcPhone:updateContact', function(id, display, phoneNumber) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] updateContact(sourcePlayer, identifier, id, phoneNumber, display) end) RegisterServerEvent('gcPhone:deleteContact') AddEventHandler('gcPhone:deleteContact', function(id) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] deleteContact(sourcePlayer, identifier, id) end) --==================================================================================== -- Messages --==================================================================================== function getMessages(identifier) local result = MySQL.Sync.fetchAll("SELECT phone_messages.* FROM phone_messages LEFT JOIN users ON users.identifier = @identifier WHERE phone_messages.receiver = users.phone_number", { ['@identifier'] = identifier }) -- A CHANGER !!!!!!! --for k, v in ipairs(result) do --v.time = os.time(v.time) + math.floor(0) - 2*60*60 --end return result --return MySQLQueryTimeStamp("SELECT phone_messages.* FROM phone_messages LEFT JOIN users ON users.identifier = @identifier WHERE phone_messages.receiver = users.phone_number", {['@identifier'] = identifier}) end local MessagesToAdd = {} AddEventHandler('playerDropped', function() local sourcePlayer = tonumber(source) if sourcePlayer ~= nil then for k,v in pairs(MessagesToAdd)do if MessagesToAdd[k] ~= nil then MySQL.Sync.execute("INSERT INTO phone_messages (`transmitter`, `receiver`, `message`, `time`, `isRead`, `owner`) VALUES(@transmitter, @receiver, @message, @time, @isRead, @owner)", { ['@transmitter'] = MessagesToAdd[k].transmitter, ['@receiver'] = MessagesToAdd[k].receiver, ['@message'] = MessagesToAdd[k].message, ['@time'] = MessagesToAdd[k].time, ['@isRead'] = MessagesToAdd[k].isRead, ['@owner'] = MessagesToAdd[k].owner }) end end end end) local function updatePlayerMessages() SetTimeout(1800000, function() for k,v in pairs(MessagesToAdd)do if MessagesToAdd[k] ~= nil then MySQL.Sync.execute("INSERT INTO phone_messages (`transmitter`, `receiver`, `message`, `time`, `isRead`, `owner`) VALUES(@transmitter, @receiver, @message, @time, @isRead, @owner)", { ['@transmitter'] = MessagesToAdd[k].transmitter, ['@receiver'] = MessagesToAdd[k].receiver, ['@message'] = MessagesToAdd[k].message, ['@time'] = MessagesToAdd[k].time, ['@isRead'] = MessagesToAdd[k].isRead, ['@owner'] = MessagesToAdd[k].owner }) end end updatePlayerMessages() end) end updatePlayerMessages() -- local lastmessage = { -- transmitter = 0, -- receiver = 0, -- message = 0, -- time = 0, -- isRead = 0, -- owner = 0, -- } function _internalAddMessage(transmitter, receiver, message, owner) print('ADD MESSAGE: ' .. transmitter .. receiver .. message .. owner) local tstamp = os.date("*t", os.time()) local time = os.date(tstamp.year .. "-" .. tstamp.month .. "-" .. tstamp.day .. " " .. tstamp.hour .. ":" .. tstamp.min .. ":" .. tstamp.sec) table.insert(MessagesToAdd, {transmitter = transmitter, receiver = receiver, message = message, isRead = 0, owner = owner, time = time, id = #MessagesToAdd+1}) return MessagesToAdd[#MessagesToAdd] end function addMessage(source, identifier, phone_number, message) local sourcePlayer = tonumber(source) local otherIdentifier = getIdentifierByPhoneNumber(phone_number) local myPhone = getNumberPhone(identifier) if otherIdentifier ~= nil then local tomess = _internalAddMessage(myPhone, phone_number, message, 0) getSourceFromIdentifier(otherIdentifier, function (osou) if tonumber(osou) ~= nil then -- TriggerClientEvent("gcPhone:allMessage", osou, getMessages(otherIdentifier)) TriggerClientEvent("gcPhone:receiveMessage", tonumber(osou), tomess) end end) end local memess = _internalAddMessage(phone_number, myPhone, message, 1) -- TriggerClientEvent("gcPhone:allMessage", source, getMessages(identifier)) TriggerClientEvent("gcPhone:receiveMessage", sourcePlayer, memess) end function setReadMessageNumber(identifier, num) local mePhoneNumber = getNumberPhone(identifier) MySQL.Sync.execute("UPDATE phone_messages SET phone_messages.isRead = 1 WHERE phone_messages.receiver = @receiver AND phone_messages.transmitter = @transmitter", { ['@receiver'] = mePhoneNumber, ['@transmitter'] = num }) end function deleteMessage(msgId) MySQL.Sync.execute("DELETE FROM phone_messages WHERE `id` = @id", { ['@id'] = msgId }) end function deleteAllMessageFromPhoneNumber(identifier, phone_number) local mePhoneNumber = getNumberPhone(identifier) MySQL.Sync.execute("DELETE FROM phone_messages WHERE `receiver` = @mePhoneNumber and `transmitter` = @phone_number", { ['@mePhoneNumber'] = mePhoneNumber, ['@phone_number'] = phone_number }) end function deleteAllMessage(identifier) local mePhoneNumber = getNumberPhone(identifier) MySQL.Sync.execute("DELETE FROM phone_messages WHERE `receiver` = @mePhoneNumber", { ['@mePhoneNumber'] = mePhoneNumber }) end RegisterServerEvent('gcPhone:sendMessage') AddEventHandler('gcPhone:sendMessage', function(phoneNumber, message) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] print(identifier) addMessage(sourcePlayer, identifier, phoneNumber, message) end) RegisterServerEvent('gcPhone:deleteMessage') AddEventHandler('gcPhone:deleteMessage', function(msgId) deleteMessage(msgId) end) RegisterServerEvent('gcPhone:deleteMessageNumber') AddEventHandler('gcPhone:deleteMessageNumber', function(number) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] deleteAllMessageFromPhoneNumber(identifier, number) TriggerClientEvent("gcPhone:allMessage", sourcePlayer, getMessages(identifier)) end) RegisterServerEvent('gcPhone:deleteAllMessage') AddEventHandler('gcPhone:deleteAllMessage', function() local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] deleteAllMessage(identifier) TriggerClientEvent("gcPhone:allMessage", sourcePlayer, getMessages(identifier)) end) RegisterServerEvent('gcPhone:setReadMessageNumber') AddEventHandler('gcPhone:setReadMessageNumber', function(num) local sourcePlayer = source local identifier = GetPlayerIdentifiers(sourcePlayer)[1] setReadMessageNumber(identifier, num) end) RegisterServerEvent('gcPhone:deleteALL') AddEventHandler('gcPhone:deleteALL', function() local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] deleteAllMessage(identifier) deleteAllContact(identifier) TriggerClientEvent("gcPhone:contactList", sourcePlayer, {}) TriggerClientEvent("gcPhone:allMessage", sourcePlayer, {}) end) --==================================================================================== -- OnLoad --==================================================================================== AddEventHandler('es:playerLoaded',function(source) local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] local myPhoneNumber = getNumberPhone(identifier) print(myPhoneNumber) while myPhoneNumber == nil or tonumber(myPhoneNumber) == 0 do local randomNumberPhone = getPhoneRandomNumber() print('TryPhone: ' .. randomNumberPhone) MySQL.Sync.execute("UPDATE users SET phone_number = @randomNumberPhone WHERE identifier = @identifier", { ['@randomNumberPhone'] = randomNumberPhone, ['@identifier'] = identifier }) myPhoneNumber = getNumberPhone(identifier) end print(myPhoneNumber) TriggerEvent("es:getPlayerFromId", sourcePlayer, function(user) user.setIdentity("phoneNumber",randomNumberPhone) end) TriggerClientEvent("gcPhone:myPhoneNumber", sourcePlayer, myPhoneNumber) TriggerClientEvent("gcPhone:contactList", sourcePlayer, getContacts(identifier)) TriggerClientEvent("gcPhone:allMessage", sourcePlayer, getMessages(identifier)) end) -- Just For reload RegisterServerEvent('gcPhone:allUpdate') AddEventHandler('gcPhone:allUpdate', function() local sourcePlayer = tonumber(source) local identifier = GetPlayerIdentifiers(sourcePlayer)[1] TriggerClientEvent("gcPhone:myPhoneNumber", sourcePlayer, getNumberPhone(identifier)) TriggerClientEvent("gcPhone:contactList", sourcePlayer, getContacts(identifier)) TriggerClientEvent("gcPhone:allMessage", sourcePlayer, getMessages(identifier)) end)
---------------------------------------------------------------------------------------------------- -- -- Copyright (c) Contributors to the Open 3D Engine Project. -- For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- -- -- ---------------------------------------------------------------------------------------------------- -- require with: -- local gameplayMultiHandler = require('scripts.utils.components.gameplayutils') -- use like: -- self.gameplayHandlers = gameplayMultiHandler.ConnectMultiHandlers{ -- [GameplayNotificationId("jump")] = { -- OnEventBegin = function(floatValue) self:JumpStart(floatValue) end, -- OnEventUpdating = function(floatValue) self:Jumping(floatValue) end, -- OnEventEnd = function(floatValue) self:JumpEnded(floatValue) end, -- }, -- } -- disconnect from like this: -- self.gameplayHandlers:Disconnect() local multiHandlers = require('scripts.utils.components.MultiHandlers') return { ConnectMultiHandlers = multiHandlers(GameplayNotificationBus, GameplayNotificationId), }
return { Points = { [9] = { x = -287.3926, scale = 0.3, y = 186 }, [2] = { x = 258.6738, scale = 0.39, y = -138 }, [3] = { x = 432.695, scale = 0.4, y = -174 }, [4] = { x = -494.4178, scale = 0.46, y = -468 }, [10] = { x = 93.65373, scale = 0.38, y = -114 }, [6] = { x = 810.741, scale = 0.42, y = -270 } }, Edges = { 2_10 = { p1 = 2, p2 = 10 }, 2_3 = { p1 = 2, p2 = 3 }, 3_6 = { p1 = 3, p2 = 6 } } }
function onCreate() makeLuaSprite('CWall', 'CWall', -800, -500); setScrollFactor('CWall', 0.9, 0.9); makeLuaSprite('CFloor', 'CFloor', -350, 300); setScrollFactor('CFloor', 1.2, 1.2); scaleObject('CFloor', 0.9, 0.9); makeAnimatedLuaSprite('anim', 'Porker Lewis', 1300, -1000); scaleObject('Porker Lewis', 0.7, 0.7); addAnimationByPrefix('anim', 'idle', 'PorkerFG', 40, true); objectPlayAnimation('anim', 'PorkerFG', false); makeAnimatedLuaSprite('float', 'Emeralds', 400, 000); addAnimationByPrefix('float', 'idle','TheEmeralds', 24, true); objectPlayAnimation('float', 'TheEmeralds', false); makeLuaSprite('pebles', 'pebles', -100, 420); setScrollFactor('pebles', 0.9, 0.9); scaleObject('pebles', 0.9, 0.9); addLuaSprite('CWall', false); addLuaSprite('Exetrees', false); addLuaSprite('CFloor', false); addLuaSprite('pebles', false); addLuaSprite('anim', true); addLuaSprite('float', true); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
require("nvim-test.runners.busted"):setup { command = "vusted", }
num_enemies = 2 boss_fight = false experience=450 gold=100 function start() addEnemy("Evil", 50, 60); addEnemy("Evil", 70, 90); end function get_speech() return nil end function get_item() if (getRandomNumber(2) == 0) then return ITEM_ELIXIR end return -1 end
config = { var0 = { tmpl1 = { tmpl2 = { class = { var0 = 1 } } } } }
------------------------------------------------------------------------------------------------ -- The Lasers module. -- -- @module lasers -- @author Łukasz Durniat -- @license MIT -- @copyright Łukasz Durniat, Mar-2018 ------------------------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------------------ -- -- MODULE DECLARATION -- -- ------------------------------------------------------------------------------------------ -- local M = {} -- ------------------------------------------------------------------------------------------ -- -- REQUIRED MODULES -- -- ------------------------------------------------------------------------------------------ -- local composer = require 'composer' -- ------------------------------------------------------------------------------------------ -- -- LOCALISED VARIABLES -- -- ------------------------------------------------------------------------------------------ -- local mSin = math.sin local mCos = math.cos local mRad = math.rad local mRandom = math.random local mSqrt = math.sqrt -- ------------------------------------------------------------------------------------------ -- -- PRIVATE METHODS -- -- ------------------------------------------------------------------------------------------ -- local function vector2DFromAngle( angle ) return { x=mCos( mRad( angle ) ), y=mSin( mRad( angle ) ) } end local function distance( x1, y1, x2, y2 ) return mSqrt( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) end -- ------------------------------------------------------------------------------------------ -- -- PUBLIC METHODS -- -- ------------------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------------------------ -- Constructor function of Ships module. -- -- @param options The table with all options for the ship. -- -- - `x`: the center x position of the ship -- - `y`: the center y position of the ship -- - `velocity`: the table with `x` and `y` fields -- -- @return The new laser instance. ------------------------------------------------------------------------------------------------ function M.new( options ) local _T = display.screenOriginY local _B = display.viewableContentHeight - display.screenOriginY local _L = display.screenOriginX local _R = display.viewableContentWidth - display.screenOriginX -- Get the current scene group local parent = display.currentStage -- Default options for instance options = options or {} local x = options.x or 0 local y = options.y or 0 local velocity = options.velocity or vector2DFromAngle( options.heading or 0 ) velocity.x = velocity.x * 0.3 velocity.y = velocity.y * 0.3 local instance = display.newRect( parent, x, y, 5, 5 ) local black = { 0, 0, 0 } instance.fill = black instance.strokeWidth = 3 instance.velocity = velocity function instance:update( dt ) self:translate( self.velocity.x * dt, self.velocity.y * dt ) end function instance:hit( asteroid ) local distanceFromObstacle = distance( self.x, self.y, asteroid.x, asteroid.y ) if distanceFromObstacle < asteroid.radius then return true else return false end end function instance:offScreen() if self.x > _R or self.x < _L then return true end if self.y > _B or self.y < _T then return true end return false end return instance end return M
local a,b=myFunc()
_addon.name = 'Itemizer' _addon.author = 'Ihina' _addon.version = '3.0.1.2' _addon.command = 'itemizer' require('luau') defaults = {} defaults.AutoNinjaTools = true defaults.AutoItems = true defaults.Delay = 0.5 defaults.version = "3.0.1.1" defaults.UseUniversalTools = {} defaults.UseUniversalTools.Katon = false defaults.UseUniversalTools.Hyoton = false defaults.UseUniversalTools.Huton = false defaults.UseUniversalTools.Doton = false defaults.UseUniversalTools.Raiton = false defaults.UseUniversalTools.Suiton = false defaults.UseUniversalTools.Utsusemi = false defaults.UseUniversalTools.Jubaku = false defaults.UseUniversalTools.Hojo = false defaults.UseUniversalTools.Kurayami = false defaults.UseUniversalTools.Dokumori = false defaults.UseUniversalTools.Tonko = false defaults.UseUniversalTools.Monomi = false defaults.UseUniversalTools.Aisha = false defaults.UseUniversalTools.Yurin = false defaults.UseUniversalTools.Myoshu = false defaults.UseUniversalTools.Migawari = false defaults.UseUniversalTools.Kakka = false defaults.UseUniversalTools.Gekka = false defaults.UseUniversalTools.Yain = false settings = config.load(defaults) bag_ids = res.bags:key_map(string.gsub-{' ', ''} .. string.lower .. table.get-{'english'} .. table.get+{res.bags}):map(table.get-{'id'}) -- Remove temporary bag, because items cannot be moved from/to there, as such it's irrelevant to Itemizer bag_ids.temporary = nil --Added this function for first load on new version. Because of the newly added features that weren't there before. windower.register_event("load", function() if settings.version == "3.0.1.1" then windower.add_to_chat(207,"Itemizer v3.0.1.2: New features added. (use //itemizer help to find out about them)") settings.version = "3.0.1.2" settings:save() end end) find_items = function(ids, bag, limit) local res = S{} local found = 0 for bag_index, bag_name in bag_ids:filter(table.get-{'enabled'} .. windower.ffxi.get_bag_info):it() do if not bag or bag_index == bag then for _, item in ipairs(windower.ffxi.get_items(bag_index)) do if ids:contains(item.id) then local count = limit and math.min(limit, item.count) or item.count found = found + count res:add({ bag = bag_index, slot = item.slot, count = count, }) if limit then limit = limit - count if limit == 0 then return res, found end end end end end end return res, found end windower.register_event("addon command", function(command, arg2, ...) if command == 'help' then local helptext = [[Itemizer - Command List:') 1. Delay <delay> - Sets the time delay. 2. Autoninjatools - toggles Automatically getting ninja tools (Shortened ant) 3. Autoitems - Toggles automatically getting items from bags (shortened ai) 4. Useuniversaltool <spell> - toggles using universal ninja tools for <spell> (shortened uut) i.e. uut katon - will toggle katon either true or false depending on your setting all defaulted false. 5. help --Shows this menu.]] for _, line in ipairs(helptext:split('\n')) do windower.add_to_chat(207, line) end elseif command:lower() == "delay" and arg2 ~= nil then if type(arg2) == 'number' then settings.delay = arg2 settings:save() else error('The delay must be a number') end elseif T{'autoninjatools','ant'}:contains(command:lower()) then settings.AutoNinjaTools = not settings.AutoNinjaTools settings:save() elseif T{'autoitems','ai'}:contains(command:lower()) then settings.AutoItems = not settings.AutoItems settings:save() elseif T{'useuniversaltool','uut'}:contains(command:lower()) then if settings.UseUniversalTools[arg2:ucfirst()] ~= nil then settings.UseUniversalTools[arg2:ucfirst()] = not settings.UseUniversalTools[arg2:ucfirst()] settings:save() else error('Argument 2 must be a ninjutsu spell (sans :ichi or :ni) i.e. uut katon') end end end) windower.register_event('unhandled command', function(command, ...) local args = L{...}:map(string.lower) if command == 'get' or command == 'put' or command == 'gets' or command == 'puts' then local count if command == 'gets' or command == 'puts' then command = command:sub(1, -2) else local last = args[#args] if last == 'all' then args:remove() elseif tonumber(last) then count = tonumber(last) args:remove() else count = 1 end end local bag = args[#args] local specified_bag = rawget(bag_ids, bag) if specified_bag then if not windower.ffxi.get_bag_info(specified_bag).enabled then error('%s currently not enabled':format(res.bags[specified_bag].name)) return end args:remove() elseif command == 'put' and not specified_bag then error('Specify a valid destination bag to put items in.') return end local source_bag local destination_bag if command == 'get' then source_bag = specified_bag destination_bag = bag_ids.inventory else destination_bag = specified_bag source_bag = bag_ids.inventory end local destination_bag_info = windower.ffxi.get_bag_info(destination_bag) if destination_bag_info.max - destination_bag_info.count == 0 then error('Not enough space in %s to move items.':format(res.bags[destination_bag].name)) return end local item_name = args:concat(' ') local item_ids = (S(res.items:name(windower.wc_match-{item_name})) + S(res.items:name_log(windower.wc_match-{item_name}))):map(table.get-{'id'}) if item_ids:length() == 0 then error('Unknown item: %s':format(item_name)) return end local matches, results = find_items(item_ids, source_bag, count) if results == 0 then error('Item "%s" not found in %s.':format(item_name, source_bag and res.bags[source_bag].name or 'any accessible bags')) return end if count and results < count then warning('Only %u "%s" found in %s.':format(results, item_name, source_bag and res.bags[source_bag].name or 'all accessible bags')) end for match in matches:it() do windower.ffxi[command .. '_item'](command == 'get' and match.bag or destination_bag, match.slot, match.count) end end end) ninjutsu = res.spells:type('Ninjutsu') patterns = L{'"(.+)"', '\'(.+)\'', '.- (.+) .-', '.- (.+)'} spec_tools = T{ Katon = 1161, Hyoton = 1164, Huton = 1167, Doton = 1170, Raiton = 1173, Suiton = 1176, Utsusemi = 1179, Jubaku = 1182, Hojo = 1185, Kurayami = 1188, Dokumori = 1191, Tonko = 1194, Monomi = 2553, Aisha = 2555, Yurin = 2643, Myoshu = 2642, Migawari = 2970, Kakka = 2644, Gekka = 8803, Yain = 8804 } gen_tools = T{ Katon = 2971, Hyoton = 2971, Huton = 2971, Doton = 2971, Raiton = 2971, Suiton = 2971, Utsusemi = 2972, Jubaku = 2973, Hojo = 2973, Kurayami = 2973, Dokumori = 2973, Tonko = 2972, Monomi = 2972, Aisha = 2973, Yurin = 2973, Myoshu = 2972, Migawari = 2972, Kakka = 2972, Gekka = 2972, Yain = 2972 } active = S{} -- Returning true resends the command in settings.Delay seconds -- Returning false doesn't resend the command and executes it collect_item = function(id, items) items = items or {inventory = windower.ffxi.get_items(bag_ids.inventory)} local item = T(items.inventory):with('id', id) if item then active = active:remove(id) return false end -- Current ID already being processed? if active:contains(id) then return true end -- Check for all items local match = find_items(S{id}, nil, 1):it()() if match then windower.ffxi.get_item(match.bag, match.slot, match.count) -- Add currently processing ID to set of active IDs active:add(id) else error('Item "%s" not found in any accessible bags':format(res.items[id].name)) end return match ~= nil end reschedule = function(text, ids, items) if not items then local info = windower.ffxi.get_bag_info(bag_ids.inventory) items = {inventory = windower.ffxi.get_items(bag_ids.inventory)} items.max_inventory = info.max items.count_inventory = info.count end -- Inventory full? if items.max_inventory - items.count_inventory == 0 then return false end for id in L(ids):it() do if collect_item(id, items) then windower.send_command:prepare('input %s':format(text)):schedule(settings.Delay) return true end end end windower.register_event('outgoing text', function() local item_names = T{} return function(text) -- Ninjutsu if settings.AutoNinjaTools and (text:startswith('/ma ') or text:startswith('/nin ') or text:startswith('/magic ') or text:startswith('/ninjutsu ')) then local name for pattern in patterns:it() do local match = text:match(pattern) if match then if ninjutsu:with('name', string.imatch-{match}) then name = match:lower():capitalize():match('%w+') break end end end if name then if settings.UseUniversalTools[name] == false or windower.ffxi.get_player().main_job ~= 'NIN' then return reschedule(text, {spec_tools[name], windower.ffxi.get_player().main_job == 'NIN' and gen_tools[name] or nil}) else return reschedule(text, {windower.ffxi.get_player().main_job == 'NIN' and gen_tools[name] or nil}) end end -- Item usage elseif settings.AutoItems and text:startswith('/item ') then local items = windower.ffxi.get_items() local inventory_items = S{} local wardrobe_items = S{} for bag in bag_ids:keyset():it() do for _, item in ipairs(items[bag]) do if item.id > 0 and not item_names[item.id] then item_names[item.id] = res.items[item.id].name end if bag == 'inventory' then inventory_items:add(item.id) elseif bag == 'wardrobe' then wardrobe_items:add(item.id) end end end local parsed_text = item_count and text:match(' (.+) (%d+)$') or text:match(' (.+)') local mid_name = parsed_text:match('"(.+)"') or parsed_text:match('\'(.+)\'') or parsed_text:match('(.+) ') local full_name = parsed_text:match('(.+)') local id = item_names:find(string.imatch-{mid_name}) or item_names:find(string.imatch-{full_name}) if id then if not inventory_items:contains(id) and not wardrobe_items:contains(id) then return reschedule(text, {id}, items) else active:remove(id) end end end end end()) --[[ Copyright © 2013-2015, Ihina All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Silence nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IHINA 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. ]] --Original plugin by Aureus
local skynet = require "skynet" local harbor = {} function harbor.globalname(name, handle) handle = handle or skynet.self() skynet.send(".cslave", "lua", "REGISTER", name, handle) end function harbor.queryname(name) return skynet.call(".cslave", "lua", "QUERYNAME", name) end function harbor.link(id) skynet.call(".cslave", "lua", "LINK", id) end function harbor.connect(id) skynet.call(".cslave", "lua", "CONNECT", id) end function harbor.linkmaster() skynet.call(".cslave", "lua", "LINKMASTER") end return harbor
-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: function lure.rom.newLineBoxObject( ) local self = lure.rom.newBoxObject( {nodeType=1, boxType=3, formatingContext=2, nodeDesc="ROMLineBoxNode"} ) --=================================================================== -- PROPERTIES = --=================================================================== self.layoutResponse = lure.rom.newLayoutResponseObject() --------------------------------------------------------------------- --==================================================================== -- METHODS = --==================================================================== self.getRemainingWidth = function() local lineBoxWidth = self.computedStyle.width local childWidths = 0 for a=1, self.childNodes.length do childWidths = childWidths + self.childNodes[a].computedStyle.width end if lineBoxWidth - childWidths >=0 then return lineBoxWidth - childWidths else return 0 end end --------------------------------------------------------------------- self.isFull = function() local totalWidth = 0 for a=1, self.childNodes.length do totalWidth = totalWidth + self.childNodes[a].computedStyle.width if totalWidth > self.computedStyle.width then return true end end return false end --------------------------------------------------------------------- self.layout = function() --lure.throw(1, "callling layout on node: " .. tostring(self.nodeDesc) .. "(FC:".. tostring(self.formatingContext) .." BT:".. tostring(self.boxType) .." NT:".. tostring(self.nodeType) ..")") self.layoutResponse.clear() self.computedStyle.left = lure.rom.computeBoxRenderStyleLeft( self ) self.computedStyle.width = lure.rom.computeBoxRenderStyleWidth( self ) self.computedStyle.top = lure.rom.computeBoxRenderStyleTop( self ) --do childlayout lure.rom.layout.doLineChildLayouts( self ) --determine line box height based on child with the largest height local height = 0 for a=1, self.childNodes.length do child = self.childNodes[a] if child.computedStyle.height >= height then height = child.computedStyle.height end end self.computedStyle.height = height or 0 return self.layoutResponse end --------------------------------------------------------------------- self.draw = function() --loop through children and call subsequent draw() methods selfCS = self.computedStyle love.graphics.setColor(192, 192, 192, 255) --love.graphics.rectangle("line", selfCS.left, selfCS.top, selfCS.width, selfCS.height ) for a=1, self.childNodes.length do local child = self.childNodes[a] child.draw() end end --------------------------------------------------------------------- return self end -- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
describe('mach.format_value', function() local format_value = require 'mach.format_value' it('should format basic types', function() assert.are.same('3', format_value(3)) assert.are.same("'hello'", format_value('hello')) assert.are.same('true', format_value(true)) end) it('should format functions', function() local f = function() end assert.are.same(tostring(f), format_value(f)) end) it('should format tables', function() assert.are.same('{ [1] = true, [2] = false }', format_value({ true, false })) assert.are.same("{ ['a'] = 1, ['b'] = 2 }", format_value({ b = 2, a = 1 })) assert.are.same( "{ [1] = true, ['b'] = { [4] = 'lua', ['a'] = 1 } }", format_value({ b = { [4] = 'lua', a = 1 }, true }) ) end) it('should respect __tostring when it is defined', function() local value = setmetatable({}, { __tostring = function() return 'foo' end }) assert.are.same('foo', format_value(value)) end) end)
PLoop(function() namespace "KittyBox.Layout" __Sealed__() class "LinearLayout"(function() inherit "ViewGroup" __Sealed__() struct "LayoutParams"(function() __base = KittyBox.Layout.LayoutParams member "gravity" { Type = Gravity } -- This property indicates the weight of the length of the child -- in the orientation of the Linearlayout to the remaining allocated space member "weight" { Type = NonNegativeNumber } end) property "Orientation" { type = Orientation, default = Orientation.HORIZONTAL, handler = function(self) self:OnViewPropertyChanged() end } -- This property determines the layout alignment of childs property "Gravity" { type = Gravity, default = Gravity.TOP + Gravity.START, handler = function(self) self:OnViewPropertyChanged() end } local function getHorizontalGravity(gravity, defaultHGravity) if Enum.ValidateFlags(Gravity.CENTER_HORIZONTAL, gravity) then return Gravity.CENTER_HORIZONTAL elseif Enum.ValidateFlags(Gravity.END, gravity) then return Gravity.END else return defaultHGravity or Gravity.START end end local function getVerticalGravity(gravity, defaultVGravity) if Enum.ValidateFlags(Gravity.CENTER_VERTICAL, gravity) then return Gravity.CENTER_VERTICAL elseif Enum.ValidateFlags(Gravity.BOTTOM, gravity) then return Gravity.BOTTOM else return defaultVGravity or Gravity.TOP end end local function layoutVertical(self) local gravity = self.Gravity local paddingStart, paddingTop, paddingEnd, paddingBottom = self.PaddingStart, self.PaddingTop, self.PaddingEnd, self.PaddingBottom local width, height = self:GetSize() local heightAvaliable = height - paddingTop - paddingBottom local widthAvaliable = width - paddingStart - paddingEnd local defaultHGravity = getHorizontalGravity(gravity) local yOffset if Enum.ValidateFlags(Gravity.CENTER_VERTICAL, gravity) then local centerYOffset = paddingTop + heightAvaliable/2 yOffset = centerYOffset - self.__ContentHeight/2 elseif Enum.ValidateFlags(Gravity.BOTTOM, gravity) then yOffset = paddingTop + heightAvaliable - self.__ContentHeight else yOffset = paddingTop end for _, child in self:GetNonGoneChilds() do child:Layout() local lp = child.LayoutParams local marginStart, marginTop, marginEnd, marginBottom = child.MarginStart, child.MarginTop, child.MarginEnd, child.MarginBottom local childHGravity = lp and getHorizontalGravity(lp.gravity, defaultHGravity) local childWidth, childHeight = child:GetSize() local xOffset if childHGravity == Gravity.CENTER_HORIZONTAL then xOffset = paddingStart + widthAvaliable/2 - (childWidth + marginStart + marginEnd)/2 elseif childHGravity == Gravity.END then xOffset = width - paddingEnd - marginEnd - childWidth else xOffset = paddingStart end yOffset = yOffset + marginTop self:LayoutChild(child, xOffset, yOffset) yOffset = yOffset + childHeight + marginBottom end end local function layoutHorizontal(self) local gravity = self.Gravity local paddingStart, paddingTop, paddingEnd, paddingBottom = self.PaddingStart, self.PaddingTop, self.PaddingEnd, self.PaddingBottom local width, height = self:GetSize() local heightAvaliable = height - paddingTop - paddingBottom local widthAvaliable = width - paddingStart - paddingEnd local defaultVGravity = getVerticalGravity(gravity) local xOffset if Enum.ValidateFlags(Gravity.CENTER_HORIZONTAL, gravity) then local centerXOffset = paddingStart + widthAvaliable/2 xOffset = centerXOffset - self.__ContentWidth/2 elseif Enum.ValidateFlags(Gravity.END, gravity) then xOffset = paddingStart + (widthAvaliable - self.__ContentWidth) else xOffset = paddingStart end for _, child in self:GetNonGoneChilds() do child:Layout() local lp = child.LayoutParams local marginStart, marginTop, marginEnd, marginBottom = child.MarginStart, child.MarginTop, child.MarginEnd, child.MarginBottom local childVGravity = lp and getVerticalGravity(lp.gravity, defaultVGravity) local childWidth, childHeight = child:GetSize() local yOffset if childVGravity == Gravity.CENTER_VERTICAL then yOffset = paddingTop + heightAvaliable/2 - (childHeight + marginTop + marginBottom)/2 elseif childVGravity == Gravity.BOTTOM then yOffset = height - paddingBottom - marginBottom - childHeight else yOffset = paddingTop end xOffset = xOffset + marginStart self:LayoutChild(child, xOffset, yOffset) xOffset = xOffset + childWidth + marginEnd end end -- Override function OnLayout(self) if self.Orientation == Orientation.HORIZONTAL then layoutHorizontal(self) else layoutVertical(self) end end local function MeasureHorizontal(self, widthMeasureSpec, heightMeasureSpec) local widthMode = MeasureSpec.GetMode(widthMeasureSpec) local heightMode = MeasureSpec.GetMode(heightMeasureSpec) local expectWidth = MeasureSpec.GetSize(widthMeasureSpec) local expectHeight = MeasureSpec.GetSize(heightMeasureSpec) local paddingStart, paddingTop, paddingEnd, paddingBottom = self.PaddingStart, self.PaddingTop, self.PaddingEnd, self.PaddingBottom local measuredWidth = paddingStart + paddingEnd local measuredHeight = 0 local totalWeight = 0 for index, child in self:GetNonGoneChilds() do local lp = child.LayoutParams totalWeight = totalWeight + (lp and lp.weight or 0) local marginStart, marginEnd, marginTop, marginBottom = child.MarginStart, child.MarginEnd, child.MarginTop, child.MarginBottom local usedHeight = paddingTop + paddingBottom + marginTop + marginBottom measuredWidth = measuredWidth + marginStart + marginEnd child:Measure(IView.GetChildMeasureSpec(widthMeasureSpec, measuredWidth, child.Width, child.MaxWidth), IView.GetChildMeasureSpec(heightMeasureSpec, usedHeight, child.Height, child.MaxHeight)) measuredWidth = measuredWidth + child:GetMeasuredWidth() measuredHeight = math.max(measuredHeight, usedHeight + child:GetMeasuredHeight()) end -- Obviously, weight only work when parent has imposed an exact size on us if widthMode == MeasureSpec.EXACTLY and totalWeight > 0 then local widthRemain = expectWidth - measuredWidth if widthRemain ~= 0 then measuredWidth = paddingStart + paddingEnd for index, child in self:GetNonGoneChilds() do local lp = child.LayoutParams if lp and lp.weight then local newWidth = math.max(0, child:GetMeasuredWidth() + widthRemain * lp.weight/totalWeight) child:Measure(MeasureSpec.MakeMeasureSpec(MeasureSpec.EXACTLY, newWidth), MeasureSpec.MakeMeasureSpec(MeasureSpec.EXACTLY, child:GetMeasuredHeight())) end measuredWidth = measuredWidth + child.MarginStart + child.MarginEnd + child:GetMeasuredWidth() end end end self.__ContentWidth = measuredWidth - paddingStart - paddingEnd self.__ContentHeight = measuredHeight - paddingTop - paddingBottom if widthMode == MeasureSpec.EXACTLY then measuredWidth = expectWidth elseif widthMode == MeasureSpec.AT_MOST then measuredWidth = math.max(self.MinWidth, math.min(expectWidth, measuredWidth)) else measuredWidth = math.max(self.MinWidth, measuredWidth) end if heightMode == MeasureSpec.EXACTLY then measuredHeight = expectHeight elseif heightMode == MeasureSpec.AT_MOST then measuredHeight = math.max(self.MinHeight, math.min(expectHeight, measuredHeight)) else measuredHeight = math.max(self.MinHeight, measuredHeight) end self:SetMeasuredSize(measuredWidth, measuredHeight) end local function MeasureVertical(self, widthMeasureSpec, heightMeasureSpec) local widthMode = MeasureSpec.GetMode(widthMeasureSpec) local heightMode = MeasureSpec.GetMode(heightMeasureSpec) local expectWidth = MeasureSpec.GetSize(widthMeasureSpec) local expectHeight = MeasureSpec.GetSize(heightMeasureSpec) local paddingStart, paddingTop, paddingEnd, paddingBottom = self.PaddingStart, self.PaddingTop, self.PaddingEnd, self.PaddingBottom local measuredWidth = 0 local measuredHeight = paddingTop + paddingBottom local totalWeight = 0 for index, child in self:GetNonGoneChilds() do local lp = child.LayoutParams totalWeight = totalWeight + (lp and lp.weight or 0) local marginStart, marginEnd, marginTop, marginBottom = child.MarginStart, child.MarginEnd, child.MarginTop, child.MarginBottom local usedWidth = paddingStart + paddingEnd + marginStart + marginEnd measuredHeight = measuredHeight + marginTop + marginBottom child:Measure(IView.GetChildMeasureSpec(widthMeasureSpec, usedWidth, child.Width, child.MaxWidth), IView.GetChildMeasureSpec(heightMeasureSpec, measuredHeight, child.Height, child.MaxHeight)) measuredWidth = math.max(measuredWidth, usedWidth + child:GetMeasuredWidth()) measuredHeight = measuredHeight + child:GetMeasuredHeight() end -- Obviously, weight only work when parent has imposed an exact size on us if heightMode == MeasureSpec.EXACTLY and totalWeight > 0 then local heightRemain = expectHeight - measuredHeight if heightRemain ~= 0 then measuredHeight = paddingTop + paddingBottom for index, child in self:GetNonGoneChilds() do local lp = child.LayoutParams if lp and lp.weight then local newHeight = math.max(0, child:GetMeasuredHeight() + heightRemain * lp.weight/totalWeight) child:Measure(MeasureSpec.MakeMeasureSpec(MeasureSpec.EXACTLY, child:GetMeasuredWidth()), MeasureSpec.MakeMeasureSpec(MeasureSpec.EXACTLY, newHeight)) end measuredHeight = measuredHeight + child.MarginTop + child.MarginBottom + child:GetMeasuredHeight() end end end self.__ContentWidth = measuredWidth - paddingStart - paddingEnd self.__ContentHeight = measuredHeight - paddingTop - paddingBottom if widthMode == MeasureSpec.EXACTLY then measuredWidth = expectWidth elseif widthMode == MeasureSpec.AT_MOST then measuredWidth = math.max(self.MinWidth, math.min(expectWidth, measuredWidth)) else measuredWidth = math.max(self.MinWidth, measuredWidth) end if heightMode == MeasureSpec.EXACTLY then measuredHeight = expectHeight elseif heightMode == MeasureSpec.AT_MOST then measuredHeight = math.max(self.MinHeight, math.min(expectHeight, measuredHeight)) else measuredHeight = math.max(self.MinHeight, measuredHeight) end self:SetMeasuredSize(measuredWidth, measuredHeight) end -- @Override function OnMeasure(self, widthMeasureSpec, heightMeasureSpec) if self.Orientation == Orientation.HORIZONTAL then MeasureHorizontal(self, widthMeasureSpec, heightMeasureSpec) else MeasureVertical(self, widthMeasureSpec, heightMeasureSpec) end end function CheckLayoutParams(self, layoutParams) if not layoutParams then return true end return Struct.ValidateValue(LinearLayout.LayoutParams, layoutParams, true) and true or false end end) end)
--[[ level.lua Provides level structures used by the generator to build maps. ]] require("entities") require("level") require("tileset") --[[ Structure The base structure. Really just exists to ensure that each structure is a class and has a build function. ]] Structure = { width = 0, height = 0, palette = 0 } function Structure:new(o) local o = o or {} setmetatable(o, self) self.__index = self return o end -- Given a cursor to the top left of the section, builds a structure of tiles within that -- section. All logic is subclass-specific; the base class does nothing. function Structure:build(topleft) -- Do nothing end --[[ BASIC STRUCTURES Structures that can be built with any tile. ]] RowStructure = Structure:new({height = 1, tile = 1}) function RowStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) for w = 1, self.width do cursor.cell:setTileByPalette(self.tile, self.palette) cursor:move(1, 0) end end ColumnStructure = Structure:new({width = 1, tile = 1}) function ColumnStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) for h = 1, self.height do cursor.cell:setTileByPalette(self.tile, self.palette) cursor:move(0, 1) end end RectangleStructure = Structure:new({tile = 1}) function RectangleStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = self.tile }) for h = 1, self.height do row:build(cursor) cursor:move(0, 1) end end -- Open corner is a numbered corner starting from top left, going clockwise StairStructure = Structure:new({tile = 0, openCorner = 1}) function StairStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = self.tile }) -- Select a corner and set up the loop step local hstep, vstep = 0, 1 if self.openCorner == 1 then -- top left cursor:move(0, self.height - 1) hstep = 1 vstep = -1 elseif self.openCorner == 2 then -- top right cursor:move(0, self.height - 1) hstep = 0 vstep = -1 elseif self.openCorner == 3 then -- bottom left hstep = 1 vstep = 1 else -- bottom right or invalid value hstep = 0 vstep = 1 end for h = 1, self.height do row:build(cursor) row.width = row.width - 1 cursor:move(hstep, vstep) end end -- Creates a checkerboard pattern of tiles. Most useful for coins. CheckerboardStructure = Structure:new({tile = COIN, startWithTile = true}) function CheckerboardStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local rowStart = Cursor:new({cell = cursor.cell}) local rowStartsWithTile = self.startWithTile for row = 1, self.height do local start = 1 if not rowStartsWithTile then start = 2 cursor:move(1, 0) end for col = start, self.width, 2 do cursor.cell:setTileByPalette(self.tile, self.palette) cursor:move(2, 0) end rowStartsWithTile = not rowStartsWithTile rowStart:move(0, 1) cursor.cell = rowStart.cell end end --[[ SOLID STRUCTURES Specialized structures with entirely solid tiles. ]] VerticalPipeStructure = Structure:new({width = 2, active = false}) function VerticalPipeStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Left side local column = ColumnStructure:new({ height = self.height, palette = self.palette, tile = VERTICAL_PIPE_LEFT_BASE }) column:build(cursor) -- Right side cursor:move(1, 0) column.tile = VERTICAL_PIPE_RIGHT_BASE column:build(cursor) -- Ends if cursor.cell.up and not cursor.cell.up:solid() and cursor.cell.up.left and not cursor.cell.up.left:solid() then cursor.cell:setTileByPalette(VERTICAL_PIPE_RIGHT_SPOUT, self.palette) cursor.cell.left:setTileByPalette(VERTICAL_PIPE_LEFT_SPOUT, self.palette) if self.active then cursor.cell.up.left.entity = PLANT end end cursor:move(0, self.height - 1) if cursor.cell.down and not cursor.cell.down:solid() and cursor.cell.down.left and not cursor.cell.down.left:solid() then cursor.cell:setTileByPalette(VERTICAL_PIPE_RIGHT_SPOUT, self.palette) cursor.cell.left:setTileByPalette(VERTICAL_PIPE_LEFT_SPOUT, self.palette) end end HorizontalPipeStructure = Structure:new({height = 2}) function HorizontalPipeStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Left side local row = RowStructure:new({ width = self.width, palette = self.palette, tile = HORIZONTAL_PIPE_UPPER_BASE }) row:build(cursor) -- Right side cursor:move(0, 1) row.tile = HORIZONTAL_PIPE_LOWER_BASE row:build(cursor) -- Ends if cursor.cell.left and not cursor.cell.left:solid() and cursor.cell.left.up and not cursor.cell.left.up:solid() then cursor.cell:setTileByPalette(HORIZONTAL_PIPE_LOWER_SPOUT, self.palette) cursor.cell.up:setTileByPalette(HORIZONTAL_PIPE_UPPER_SPOUT, self.palette) end cursor:move(self.width - 1, 0) if cursor.cell.right and not cursor.cell.right:solid() and cursor.cell.right.up and not cursor.cell.right.up:solid() then cursor.cell:setTileByPalette(HORIZONTAL_PIPE_LOWER_SPOUT, self.palette) cursor.cell.up:setTileByPalette(HORIZONTAL_PIPE_UPPER_SPOUT, self.palette) end end BlasterStructure = Structure:new({width = 1, active = false}) function BlasterStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local column = ColumnStructure:new({ height = self.height, palette = self.palette, tile = BLASTER_BASE }) column:build(cursor) cursor.cell:setTileByPalette(BLASTER_TOP, self.palette) if self.active then cursor.cell.entity = BULLETBILL end cursor:move(0, 1) cursor.cell:setTileByPalette(BLASTER_MOUNT, self.palette) end CloudPlatformStructure = Structure:new({height = 1}) function CloudPlatformStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = CLOUD_PLATFORM_CENTER }) row:build(cursor) cursor.cell:setTileByPalette(CLOUD_PLATFORM_LEFT, self.palette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(CLOUD_PLATFORM_RIGHT, self.palette) end --[[ SEMISOLID STRUCTURES Specialized structures with some solid and nonsolid tiles. ]] TreetopsStructure = Structure:new({ treePalette = 0, basePalette = 0, altTree = false, altBase = false}) function TreetopsStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Base of the tree local baseOffset = self.altBase and TREETOPS_BASE_ALT_OFFSET or 0 local base = RectangleStructure:new({ width = self.width - 2, height = self.height, palette = self.basePalette, tile = TREETOPS_BASE + baseOffset }) -- Top of the tree local treeOffset = self.altTree and TREETOPS_ALT_OFFSET or 0 local tree = RowStructure:new({ width = self.width, palette = self.treePalette, tile = TREETOPS_CENTER + treeOffset }) -- Build the tree cursor:move(1, 0) base:build(cursor) cursor:move(-1, 0) tree:build(cursor) cursor.cell:setTileByPalette(TREETOPS_LEFT + treeOffset, self.treePalette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(TREETOPS_RIGHT + treeOffset, self.treePalette) end MushroomStructure = Structure:new({basePalette = 0, mushroomPalette = 0}) function MushroomStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Stalk cursor:move(math.ceil(self.width / 2) - 1, 0) local stalk = ColumnStructure:new({ height = self.height, palette = self.basePalette, tile = MUSHROOM_PLATFORM_BASE }) stalk:build(cursor) if cursor.cell.down then cursor.cell.down:setTileByPalette(MUSHROOM_PLATFORM_STALK, self.basePalette) end -- Platform cursor.cell = topleft.cell local platform = RowStructure:new({ width = self.width, palette = self.mushroomPalette, tile = MUSHROOM_PLATFORM_CENTER }) platform:build(cursor) cursor.cell:setTileByPalette(MUSHROOM_PLATFORM_LEFT, self.mushroomPalette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(MUSHROOM_PLATFORM_RIGHT, self.mushroomPalette) end SkyBridgeStructure = Structure:new({ basePalette = 0, ropePalette = 0, altBridge = false, blockTile = 0}) function SkyBridgeStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Ropes local row = RowStructure:new({ width = self.width, palette = self.ropePalette, tile = SKY_BRIDGE_ROPE }) row:build(cursor) -- Bridge local offset = self.altBridge and SKY_BRIDGE_ALT_OFFSET or 0 row.palette = self.basePalette row.tile = SKY_BRIDGE + offset cursor:move(0, self.height > 1 and 1 or 0) row:build(cursor) -- Supports (if applicable) if self.height <= 2 then return end local column = ColumnStructure:new({ height = self.height - 1, palette = self.basePalette, tile = self.blockTile }) column:build(cursor) cursor:move(self.width - 1, 0) column:build(cursor) end CastleBridgeStructure = Structure:new({active = false}) function CastleBridgeStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) -- Bridge local row = RowStructure:new({ width = self.width, palette = self.palette, tile = CASTLE_BRIDGE }) cursor:move(0, self.height - 1) row:build(cursor) if self.active then cursor.cell.entity = BOWSER end -- Chain cursor:move(math.max(self.width - self.height + 1, 0), -1) for i = 1, math.min(self.width, self.height - 1) do cursor.cell:setTileByPalette(CASTLE_BRIDGE_CHAIN, self.palette) cursor:move(1, -1) end if self.active then cursor.cell.entity = AXE end end FlagpoleStructure = Structure:new({ width = 1, basePalette = 0, polePalette = 0, blockTile = FIRST_BLOCK_TILE, active = false}) function FlagpoleStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local column = ColumnStructure:new({ height = self.height, palette = self.polePalette, tile = FLAGPOLE }) column:build(cursor) cursor.cell:setTileByPalette(FLAGPOLE_TOP, self.polePalette) cursor:move(0, self.height - 1) cursor.cell:setTileByPalette(self.blockTile, self.basePalette) if self.active then cursor.cell.entity = FLAG end end --[[ BACKGROUND STRUCTURES Specialized structures with no solid tiles. ]] HillStructure = Structure:new({width = 0}) function HillStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) for row = 1, self.height do local width = row * 2 - 1 for col = 1, width do if width == 1 then cursor.cell:setTileByPalette(HILL_TOP, self.palette) elseif col == 1 then cursor.cell:setTileByPalette(HILL_LEFT, self.palette) elseif row <= 3 and col == 2 then cursor.cell:setTileByPalette(HILL_TREES, self.palette) elseif row <= 3 and col == width - 1 then cursor.cell:setTileByPalette( HILL_TREES + HILL_TREES_ALT_OFFSET, self.palette) elseif col == width then cursor.cell:setTileByPalette(HILL_RIGHT, self.palette) else cursor.cell:setTileByPalette(HILL_INSIDE, self.palette) end cursor:move(1, 0) end cursor:move(-width - 1, 1) end end LavaStructure = Structure:new() function LavaStructure:build(topleft) local rect = RectangleStructure:new({ width = self.width, height = self.height, palette = self.palette, tile = LAVA_CENTER }) rect:build(topleft) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = LAVA_TOP }) row:build(topleft) end BushStructure = Structure:new({height = 1}) function BushStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = BUSH_CENTER }) row:build(cursor) cursor.cell:setTileByPalette(BUSH_LEFT, self.palette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(BUSH_RIGHT, self.palette) end CloudStructure = Structure:new({height = 2}) function CloudStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local row = RowStructure:new({ width = self.width, palette = self.palette, tile = CLOUD_UPPER_CENTER }) row:build(cursor) cursor:move(0, 1) row.tile = CLOUD_LOWER_CENTER row:build(cursor) cursor.cell:setTileByPalette(CLOUD_LOWER_LEFT, self.palette) cursor.cell.up:setTileByPalette(CLOUD_UPPER_LEFT, self.palette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(CLOUD_LOWER_RIGHT, self.palette) cursor.cell.up:setTileByPalette(CLOUD_UPPER_RIGHT, self.palette) end TreeStructure = Structure:new({ width = 1, treePalette = 0, trunkPalette = 0, altTree = false}) function TreeStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local offset = self.altTree and BG_TREE_ALT_OFFSET or 0 for row = 1, self.height do if row == 1 and row == self.height - 1 then cursor.cell:setTileByPalette( SMALL_BG_TREE + offset, self.treePalette) elseif row == 1 then cursor.cell:setTileByPalette( LARGE_BG_TREE_UPPER + offset, self.treePalette) elseif row == self.height - 1 then cursor.cell:setTileByPalette( LARGE_BG_TREE_LOWER + offset, self.treePalette) elseif row == self.height then cursor.cell:setTileByPalette(BG_TREE_BASE, self.trunkPalette) else cursor.cell:setTileByPalette( LARGE_BG_TREE_CENTER + offset, self.treePalette) end cursor:move(0, 1) end end CastleStructure = Structure:new({width = 5, height = 5, altBrick = false}) function CastleStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) local offset = self.altBrick and CASTLE_ALT_OFFSET or 0 -- First row (roof) cursor:move(1, 0) local row = RowStructure:new({ width = self.width - 2, palette = self.palette, tile = CASTLE_TOP + offset }) row:build(cursor) -- Second row (windows) cursor:move(0, 1) row.tile = CASTLE_WALL + offset row:build(cursor) cursor.cell:setTileByPalette(CASTLE_LEFT_WINDOW + offset, self.palette) cursor:move(self.width - 3, 0) cursor.cell:setTileByPalette(CASTLE_RIGHT_WINDOW + offset, self.palette) -- Third row (rampart) cursor:move(3 - self.width, 1) row.tile = CASTLE_RAMPART + offset row:build(cursor) cursor:move(-1, 0) cursor.cell:setTileByPalette(CASTLE_TOP + offset, self.palette) cursor:move(self.width - 1, 0) cursor.cell:setTileByPalette(CASTLE_TOP + offset, self.palette) cursor:move(1 - self.width, 0) -- All other rows row.width = self.width row.tile = CASTLE_WALL + offset for i = 4, self.height do cursor:move(0, 1) row:build(cursor) end -- Door cursor:move(math.floor(self.width / 2), 0) cursor.cell:setTileByPalette(DOOR, self.palette) cursor:move(0, -1) cursor.cell:setTileByPalette(CASTLE_DOORWAY + offset, self.palette) end --[[ UTILITY STRUCTURES Structures that alter what already exists rather than building something new. ]] NonsolidStructure = Structure:new() function NonsolidStructure:build(topleft) local cursor = Cursor:new({cell = topleft.cell}) for row = 1, self.height do for col = 1, self.width do if cursor.cell:solid() then cursor.cell.tile = cursor.cell.tile + LAST_SOLID_TILE end cursor:move(1, 0) end cursor.cell = topleft.cell cursor:move(0, row) end end
local ctypes = {} local util = require("titan-compiler.util") local inspect = require("inspect") local typed = require("typed") local equal_declarations local add_type = typed("TypeList, string, CType -> ()", function(lst, name, typ) lst[name] = typ table.insert(lst, { name = name, type = typ }) end) -- Compare two lists of declarations local equal_lists = typed("array, array -> boolean", function(l1, l2) if #l1 ~= #l2 then return false end for i, p1 in ipairs(l1) do local p2 = l2[i] if not equal_declarations(p1, p2) then return false end end return true end) equal_declarations = function(t1, t2) if type(t1) == "string" or type(t2) == "nil" then return t1 == t2 end if not equal_declarations(t1.type, t2.type) then return false end -- if not equal_lists(t1.name, t2.name) then -- return false -- end if t1.type == "struct" then if t1.name ~= t2.name then return false end elseif t1.type == "function" then if not equal_declarations(t1.ret.type, t2.ret.type) then return false end if not equal_lists(t1.params, t2.params) then return false end if t1.vararg ~= t2.vararg then return false end end return true end local function is_modifier(str) return str == "*" or str == "restrict" or str == "const" end local function extract_modifiers(ret_pointer, items) while is_modifier(items[1]) do table.insert(ret_pointer, table.remove(items, 1)) end end local function get_name(name_src) local ret_pointer = {} if name_src == nil then return false, "could not find a name: " .. inspect(name_src), nil end local name local indices = {} if type(name_src) == "string" then if is_modifier(name_src) then table.insert(ret_pointer, name_src) else name = name_src end else name_src = name_src.declarator or name_src if type(name_src[1]) == "table" then extract_modifiers(ret_pointer, name_src[1]) else extract_modifiers(ret_pointer, name_src) end for _, part in ipairs(name_src) do if part.idx then table.insert(indices, part.idx) end end name = name_src.name end return true, name, ret_pointer, next(indices) and indices end local get_type local get_fields local convert_value = typed("TypeList, table -> CType?, string?", function (lst, src) local name = nil local ret_pointer = {} local idxs = nil if type(src.id) == "table" or type(src.ids) == "table" then -- FIXME multiple ids, e.g.: int *x, y, *z; local ok ok, name, ret_pointer, idxs = get_name(src.id or src.ids) if not ok then return nil, name end end local typ, err = get_type(lst, src, ret_pointer) if not typ then return nil, err end return typed.table("CType", { name = name, type = typ, idxs = idxs, }), nil end) -- Interpret field data from `field_src` and add it to `fields`. local function add_to_fields(lst, field_src, fields) if type(field_src) == "table" and not field_src.ids then assert(field_src.type.type == "union") local subfields = get_fields(lst, field_src.type.fields) for _, subfield in ipairs(subfields) do table.insert(fields, subfield) end return true end local field, err = convert_value(lst, field_src) if not field then return nil, err end table.insert(fields, field) return true end get_fields = function(lst, fields_src) local fields = {} for _, field_src in ipairs(fields_src) do local ok, err = add_to_fields(lst, field_src, fields) if not ok then return false, err end end return fields end local function get_enum_items(_, values) local items = {} for _, v in ipairs(values) do -- TODO store enum actual values table.insert(items, { name = v.id }) end return items end local get_composite_type = typed("TypeList, string?, string, array, string, function -> CType, string", function(lst, specid, spectype, parts, partsfield, get_parts) local name = specid local key = spectype .. "@" .. (name or tostring(parts)) if not lst[key] then -- Forward declaration lst[key] = typed.table("CType", { type = spectype, name = name, }) end if parts then local err parts, err = get_parts(lst, parts) if not parts then return nil, err end end local typ = typed.table("CType", { type = spectype, name = name, [partsfield] = parts, }) if lst[key] then if typ[partsfield] and lst[key][partsfield] and not equal_declarations(typ, lst[key]) then return nil, "redeclaration for " .. key end end add_type(lst, key, typ) return typ, key end) local function get_structunion(lst, spec) if spec.fields and not spec.fields[1] then spec.fields = { spec.fields } end return get_composite_type(lst, spec.id, spec.type, spec.fields, "fields", get_fields) end local function get_enum(lst, spec) if spec.values and not spec.values[1] then spec.values = { spec.values } end local typ, key = get_composite_type(lst, spec.id, spec.type, spec.values, "values", get_enum_items) if typ.values then for _, value in ipairs(typ.values) do add_type(lst, value.name, typ) end end return typ, key end local function refer(lst, item, get_fn) if item.id and not item.fields then local key = item.type .. "@" .. item.id local su_typ = lst[key] if not su_typ then return { type = item.type, name = { item.id }, } end return su_typ else local typ, key = get_fn(lst, item) if not typ then return nil, key end return typ end end local calculate local function binop(val, fn) local e1, e2 = calculate(val[1]), calculate(val[2]) if type(e1) == "number" and type(e2) == "number" then return fn(e1, e2) else return { e1, e2, op = val.op } end end calculate = function(val) if type(val) == "string" then return tonumber(val) end if val.op == "+" then return binop(val, function(a, b) return a + b end) elseif val.op == "-" then return binop(val, function(a, b) return a - b end) elseif val.op == "*" then return binop(val, function(a, b) return a * b end) elseif val.op == "/" then return binop(val, function(a, b) return a / b end) else return val end end local base_types = { ["char"] = true, ["const"] = true, ["double"] = true, ["float"] = true, ["int"] = true, ["long"] = true, ["short"] = true, ["signed"] = true, ["unsigned"] = true, ["void"] = true, ["volatile"] = true, ["_Bool"] = true, ["_Complex"] = true, ["*"] = true, } local qualifiers = { ["extern"] = true, ["static"] = true, ["typedef"] = true, ["restrict"] = true, ["inline"] = true, ["register"] = true, } get_type = function(lst, spec, ret_pointer) local tarr = {} if type(spec.type) == "string" then spec.type = { spec.type } end if spec.type and not spec.type[1] then spec.type = { spec.type } end for _, part in ipairs(spec.type or spec) do if qualifiers[part] then -- skip elseif base_types[part] then table.insert(tarr, part) elseif lst[part] and lst[part].type == "typedef" then table.insert(tarr, part) elseif type(part) == "table" and part.type == "struct" or part.type == "union" then local su_typ, err = refer(lst, part, get_structunion) if not su_typ then return nil, err or "failed to refer struct" end table.insert(tarr, su_typ) elseif type(part) == "table" and part.type == "enum" then local en_typ, err = refer(lst, part, get_enum) if not en_typ then return nil, err or "failed to refer enum" end table.insert(tarr, en_typ) else return nil, "FIXME unknown type " .. inspect(spec) end end if #ret_pointer > 0 then for _, item in ipairs(ret_pointer) do if type(item) == "table" and item.idx then table.insert(tarr, { idx = calculate(item.idx) }) else table.insert(tarr, item) end end end return tarr, nil end local function is_void(param) return #param.type == 1 and param.type[1] == "void" end local get_params = typed("TypeList, array -> array, boolean", function(lst, params_src) local params = {} local vararg = false assert(not params_src.param) for _, param_src in ipairs(params_src) do if param_src == "..." then vararg = true else local param, err = convert_value(lst, param_src.param) if not param then return nil, err end if not is_void(param) then table.insert(params, param) end end end return params, vararg end) local register_many = function(register_item_fn, lst, ids, spec) for _, id in ipairs(ids) do local ok, err = register_item_fn(lst, id, spec) if not ok then return false, err end end return true, nil end local register_decl_item = function(lst, id, spec) local ok, name, ret_pointer, idxs = get_name(id.decl) if not ok then return false, name end assert(name) local ret_type, err = get_type(lst, spec, ret_pointer) if not ret_type then return false, err end local typ if id.decl.params then local params, vararg = get_params(lst, id.decl.params) if not params then return false, vararg end typ = typed.table("CType", { type = "function", name = name, idxs = idxs, ret = { type = ret_type, }, params = params, vararg = vararg, }) else typ = typed.table("CType", { type = ret_type, name = name, idxs = idxs, }) end if lst[name] then if not equal_declarations(lst[name], typ) then return false, "inconsistent declaration for " .. name .. " - " .. inspect(lst[name]) .. " VERSUS " .. inspect(typ) end end add_type(lst, name, typ) return true, nil end local register_decls = function(lst, ids, spec) return register_many(register_decl_item, lst, ids, spec) end -- Convert an table produced by an `extern inline` declaration -- into one compatible with `register_decl`. local function register_function(lst, item) local id = { decl = { name = item.func.name, params = item.func.params, } } return register_decl_item(lst, id, item.spec) end local function register_static_function(lst, item) return true end local register_typedef_item = typed("TypeList, table, table -> boolean, string?", function(lst, id, spec) local ok, name, ret_pointer = get_name(id.decl) if not ok then return false, name or "failed" end local def, err = get_type(lst, spec, ret_pointer) if not def then return false, err or "failed" end local typ = typed.table("CType", { type = "typedef", name = name, def = def, }) if lst[name] then if not equal_declarations(lst[name], typ) then return false, "inconsistent declaration for " .. name .. " - " .. inspect(lst[name]) .. " VERSUS " .. inspect(typ) end end add_type(lst, name, typ) return true, nil end) local register_typedefs = function(lst, item) return register_many(register_typedef_item, lst, item.ids, item.spec) end local function register_structunion(lst, item) return get_structunion(lst, item.spec) end local function register_enum(lst, item) return get_enum(lst, item.spec) end ctypes.register_types = typed("{Decl} -> TypeList?, string?", function(parsed) local lst = typed.table("TypeList", {}) for _, item in ipairs(parsed) do typed.check(item.spec, "table") local spec_set = util.to_set(item.spec) if spec_set.extern and item.ids then local ok, err = register_decls(lst, item.ids, item.spec) if not ok then return nil, err or "failed extern" end elseif spec_set.extern and item.func then local ok, err = register_function(lst, item) if not ok then return nil, err or "failed extern" end elseif spec_set.static and item.func then local ok, err = register_static_function(lst, item) if not ok then return nil, err or "failed static function" end elseif spec_set.typedef then local ok, err = register_typedefs(lst, item) if not ok then return nil, err or "failed typedef" end elseif item.spec.type == "struct" or item.spec.type == "union" then local ok, err = register_structunion(lst, item) if not ok then return nil, err or "failed struct/union" end elseif item.spec.type == "enum" then local ok, err = register_enum(lst, item) if not ok then return nil, err or "failed enum" end elseif not item.ids then -- forward declaration (e.g. "struct foo;") elseif item.ids then local ok, err = register_decls(lst, item.ids, item.spec) if not ok then return nil, err or "failed declaration" end else return nil, "FIXME Uncategorized declaration: " .. inspect(item) end end return lst, nil end) return ctypes
R'commented'.setup { hooks = { before_comment = require('ts_context_commentstring.internal').update_commentstring, }, comment_padding = ' ', keybindings = { n = ',c', v = ',c', nl = ',c' }, prefer_block_comment = false, set_keybindings = true, ex_mode_cmd = 'Comment', }
-- hammerspoon config require('luarocks.loader') require('modules.inputsource_aurora') -- Hammerspoon reload hs.hotkey.bind({'option', 'cmd'}, 'r', hs.reload) -- WindowHints hs.hints.hintChars = {'1', '2', '3', '4', 'Q', 'W', 'E', 'R'} hs.hotkey.bind({'shift'}, 'F1', hs.hints.windowHints) local f13_mode = hs.hotkey.modal.new() hs.hotkey.bind({}, 'f13', function() f13_mode:enter() end, function() f13_mode:exit() end) local f14_mode = hs.hotkey.modal.new() hs.hotkey.bind({}, 'f14', function() f14_mode:enter() end, function() f14_mode:exit() end) do -- hints -- hs.hotkey.bind({}, 'f16', hs.hints.windowHints) -- hs.hints.hintChars = {'q', 'w', 'e', 'r', 'u', 'i', 'o', 'p', 'h', 'j', 'k', 'l', 'm', ',', '.' } end do -- app manager local app_man = require('modules.appman') local mode = f13_mode mode:bind({}, 'c', app_man:toggle('Google Chrome')) mode:bind({}, 'l', app_man:toggle('Line')) mode:bind({}, 'q', app_man:toggle('Sequel Pro')) -- mode:bind({'shift'}, 'v', app_man:toggle('VimR')) -- mode:bind({}, 'v', app_man:toggle('MacVim')) mode:bind({}, 't', app_man:toggle('Terminal')) mode:bind({}, 'b', app_man:toggle('Ridibooks')) mode:bind({}, 'm', app_man:toggle('Notes')) mode:bind({}, 'n', app_man:toggle('Notion')) mode:bind({}, 's', app_man:toggle('Slack')) mode:bind({}, 'f', app_man:toggle('Finder')) mode:bind({}, 'r', app_man:toggle('Reminders')) mode:bind({}, 'e', app_man:toggle('Evernote')) mode:bind({}, 'w', app_man:toggle('WebStorm')) mode:bind({}, 'd', app_man:toggle('ScreenBrush')) mode:bind({}, 'a', app_man:toggle('Atom')) mode:bind({}, 'p', app_man:toggle('Preview')) -- mode:bind({}, 'p', app_man:toggle('PhpStorm')) mode:bind({}, 'k', app_man:toggle('KakaoTalk')) -- mode:bind({}, 't', app_man:toggle('Telegram')) mode:bind({}, 'i', app_man:toggle('iTerm')) mode:bind({}, 'v', app_man:toggle('Visual Studio Code')) -- mode:bind({'shift'}, 'tab', app_man.focusPreviousScreen) mode:bind({}, 'tab', app_man.focusNextScreen) -- hs.hotkey.bind({'cmd', 'shift'}, 'space', app_man:toggle('Terminal')) local tabTable = {} tabTable['Slack'] = { left = {mod = {'option'}, key = 'up'}, right = {mod = {'option'}, key = 'down'} } tabTable['Safari'] = { left = {mod = {'control', 'shift'}, key = 'tab'}, right = {mod = {'control'}, key = 'tab'} } tabTable['터미널'] = { left = {mod = {'control', 'shift'}, key = 'tab'}, right = {mod = {'control'}, key = 'tab'} } tabTable['Terminal'] = { left = {mod = {'control', 'shift'}, key = 'tab'}, right = {mod = {'control'}, key = 'tab'} } tabTable['iTerm2'] = { left = {mod = {'control', 'shift'}, key = 'tab'}, right = {mod = {'control'}, key = 'tab'} } tabTable['IntelliJ IDEA'] = { left = {mod = {'command', 'shift'}, key = '['}, right = {mod = {'command', 'shift'}, key = ']'} } tabTable['PhpStorm'] = { left = {mod = {'command', 'shift'}, key = '['}, right = {mod = {'command', 'shift'}, key = ']'} } tabTable['WebStorm'] = { left = {mod = {'command', 'shift'}, key = '['}, right = {mod = {'command', 'shift'}, key = ']'} } tabTable['_else_'] = { left = {mod = {'control'}, key = 'pageup'}, right = {mod = {'control'}, key = 'pagedown'} } local function tabMove(dir) return function() local activeAppName = hs.application.frontmostApplication():name() local tab = tabTable[activeAppName] or tabTable['_else_'] hs.eventtap.keyStroke(tab[dir]['mod'], tab[dir]['key']) end end f13_mode:bind({}, ',', tabMove('left'), function() end, tabMove('left')) f13_mode:bind({}, '.', tabMove('right'), function() end, tabMove('right')) end do -- winmove local win_move = require('modules.hammerspoon_winmove.hammerspoon_winmove') local mode = f14_mode mode:bind({}, '0', win_move.default) mode:bind({}, '1', win_move.left_bottom) mode:bind({}, '2', win_move.bottom) mode:bind({}, '3', win_move.right_bottom) mode:bind({}, '4', win_move.left) mode:bind({}, '5', win_move.full_screen) mode:bind({}, '6', win_move.right) mode:bind({}, '7', win_move.left_top) mode:bind({}, '8', win_move.top) mode:bind({}, '9', win_move.right_top) mode:bind({}, '-', win_move.prev_screen) mode:bind({}, '=', win_move.next_screen) mode:bind({}, 'a', win_move.more_left_padding) mode:bind({}, 'd', win_move.more_right_padding) mode:bind({}, 'w', win_move.more_up_padding) mode:bind({}, 's', win_move.more_down_padding) end do -- clipboard history local clipboard = require('modules.clipboard') local mode = f13_mode clipboard.setSize(10) f13_mode:bind({}, '`', clipboard.showList) f13_mode:bind({'shift'}, '`', clipboard.clear) end hs.alert.show('loaded')
local diff_table = {} local item_attributes = {} local max_durability = tonumber(minetest.settings:get("crafting_durability.max_durability_limit")) or 1000 ------------------------------------------- ---- Local functions ------------------------------------------- local function register_crafting_durability() -- Create diff value table for dur = 2, max_durability do local wear if dur > 256 then wear = math.floor(65535 / (dur - 1)) else wear = math.floor(65535 / dur + 1) end local diff = 65536 - (wear * dur) if diff > 0 then diff_table[dur] = diff end end -- Create item attributes table for name, def in pairs(minetest.registered_tools) do local dur = 0 local tbl = nil if type(def.crafting_durability) == "table" then tbl = def.crafting_durability dur = tonumber(tbl.durability) or 0 else dur = tonumber(def.crafting_durability) or 0 end dur = math.min(dur, max_durability) if (dur > 1 or tbl) and not def.tool_capabilities then item_attributes[name] = { add_wear = 0, durability = dur, need_replacements = false, check_string = "", } local attr = item_attributes[name] if dur > 1 then if dur > 256 then attr.add_wear = math.floor(65535 / (dur - 1)) else attr.add_wear = math.floor(65535 / dur + 1) end end if tbl then attr.need_replacements = tbl.need_replacements or false attr.check_string = tbl.need_replacements and name or "" end end end end local function is_repair(output_itemname, craft_grid) local check_list = {} local item_kind = 0 for _, old_stack in ipairs(craft_grid) do local name = old_stack:get_name() if name ~= "" then if not check_list[name] then check_list[name] = true item_kind = item_kind + 1 end end end if (item_kind == 1) and (output_itemname == next(check_list, nil)) then return true end return false end ------------------------------------------- ---- Register callbacks ------------------------------------------- minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if is_repair(itemstack:get_name(), old_craft_grid) then return itemstack end local new_craft_grid = craft_inv:get_list("craft") for idx, old_stack in ipairs(old_craft_grid) do local attr = item_attributes[old_stack:get_name()] if attr and (attr.durability > 1) and (new_craft_grid[idx]:get_name() == attr.check_string) then local diff = diff_table[attr.durability] local new_stack = ItemStack(old_stack) if diff and (new_stack:get_wear() == 0) then new_stack:set_wear(diff) end new_stack:add_wear(attr.add_wear) craft_inv:set_stack("craft", idx, new_stack) end end return itemstack end) ------------------------------------------- ---- Register crafting durability ------------------------------------------- minetest.after(1, register_crafting_durability) minetest.log("action", "[Crafting Durability] Loaded!")
local dna = LibStub("AceAddon-3.0"):GetAddon("dna") local L = LibStub("AceLocale-3.0"):GetLocale("dna") dna.class_action = {} dna.class_action.__index = dna.class_action --[[ -- syntax equivalent to "MyClass.new = function..." function MyClass.new(init) local self = setmetatable({}, MyClass) self.value = init return self end function MyClass.set_value(self, newval) self.value = newval end function MyClass.get_value(self) return self.value end local i = MyClass.new(5) -- tbl:name(arg) is a shortcut for tbl.name(tbl, arg), except tbl is evaluated only once print(i:get_value()) --> 5 i:set_value(6) print(i:get_value()) --> 6 --]] --***************************************************** --Action Utility functions --***************************************************** function dna.AddAction( ActionName, ShowError, ActionType, Att1, Att2, X,Y,H,W, Criteria) if ( dna.ui.EntryHasErrors( ActionName ) ) then if ( dna.ui.sgMain ) then dna.ui.fMain:SetStatusText( string.format(L["common/error/unsafestring"], ActionName) ) end return end -- Create the rotation if needed -- dna:dprint("AddAction to rotationname="..dna.D.ImportName) local lRotationKey = nil if ( dna.D.ImportType and dna.D.ImportType == 'actionpack' and dna.D.OTM[dna.D.PClass].selectedrotationkey ) then lRotationKey = dna.D.OTM[dna.D.PClass].selectedrotationkey else lRotationKey = dna:SearchTable(dna.D.RTMC, "text", dna.D.ImportName) end -- dna:dprint("AddAction lRotationKey="..tostring(lRotationKey)) if ( not lRotationKey ) then if ( dna.ui.fMain and dna.ui.fMain:IsShown() ) then dna.ui.fMain:SetStatusText( L["rotations/rimportfail/E6"] ) end print( L["utils/debug/prefix"]..L["rotations/rimportfail/E5"] ) return end -- Create the action local lActionExists = dna:SearchTable(dna.D.RTMC[lRotationKey].children, "text", ActionName) local lNewActionValue = 'dna.ui:CAP([=['..ActionName..']=])' local lNewActionText = ActionName if ( dna.D.UpdateMode==0 and lActionExists ) then -- dna:dprint("found duplicate action="..ActionName.." dna.D.UpdateMode="..dna.D.UpdateMode) local iSuffix = 0 lNewActionText = lNewActionText..'_' while lActionExists do iSuffix = iSuffix+1 lActionExists = dna:SearchTable(dna.D.RTMC[lRotationKey].children, "text", lNewActionText..iSuffix) end lNewActionValue = 'dna.ui:CAP([=['..lNewActionText..iSuffix..']=])' lNewActionText = lNewActionText..iSuffix end local lNewAction = { value = lNewActionValue, text = lNewActionText} lActionExists = dna:SearchTable(dna.D.RTMC[lRotationKey].children, "text", lNewActionText) if ( lActionExists ) then if ( dna.ui.sgMain and ShowError ) then dna.ui.fMain:SetStatusText( string.format(L["common/error/exists"], lNewActionText) ) end if ( dna.ui.sgMain ) then dna.ui.fMain:SetStatusText( '' ) end -- Clear any previous errors if ( dna.D.ImportType and dna.D.ImportType == 'rotation' ) then table.insert( dna.D.RTMC[lRotationKey].children, lNewAction) else dna.D.ImportIndex = dna.D.ImportIndex + 1 table.insert( dna.D.RTMC[lRotationKey].children, dna.D.ImportIndex, lNewAction) end else if ( dna.ui.sgMain ) then dna.ui.fMain:SetStatusText( '' ) end -- Clear any previous errors if ( dna.D.ImportType and dna.D.ImportType == 'rotation' ) then table.insert( dna.D.RTMC[lRotationKey].children, lNewAction) else dna.D.ImportIndex = dna.D.ImportIndex + 1 table.insert( dna.D.RTMC[lRotationKey].children, dna.D.ImportIndex, lNewAction) end end lActionExists = dna:SearchTable(dna.D.RTMC[lRotationKey].children, "text", lNewActionText) if ( lActionExists ) then local ActionDB = dna.D.RTMC[lRotationKey].children[lActionExists] if ( not dna.IsBlank(ActionType) ) then ActionDB.at = ActionType end if ( not dna.IsBlank(Att1) ) then ActionDB.att1 = Att1 end if ( not dna.IsBlank(Att2) ) then ActionDB.att2 = Att2 end if ( not dna.IsBlank(X) and dna.IsBlank(ActionDB.x) ) then ActionDB.x = X end --Only update if the database is blank and the update is not blank if ( not dna.IsBlank(Y) and dna.IsBlank(ActionDB.y) ) then ActionDB.y = Y end if ( not dna.IsBlank(H) and dna.IsBlank(ActionDB.h) ) then ActionDB.h = H end if ( not dna.IsBlank(W) and dna.IsBlank(ActionDB.w) ) then ActionDB.w = W end if ( not dna.IsBlank(Criteria) ) then ActionDB.criteria = Criteria end end if ( dna.ui.sgMain ) then dna.ui.sgMain.tgMain:RefreshTree() end --TODO: Add reinit any overlays here return lNewActionText, lActionExists end function dna.fActionSave() -- Create the criteria function from the ActionDB.criteria field -- local dnaSABFrame = nil -- dna:dprint(GetTime().."dna.fActionSave dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].criteria="..tostring(dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].criteria)) local ret1 if (string.find( dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].criteria or "", '--_dna_enable_lua' ) ) then dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].fCriteria, ret1=loadstring(dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].criteria or "return false") -- Create Function for engine to check the criteria with full lua allowed in criteria else -- dna:dprint(GetTime().."dna.fActionSave lua not enabled") dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].fCriteria, ret1=loadstring("return "..(dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].criteria or "false")) -- Create Function for engine to check the criteria with prepended return -- dna:dprint(GetTime().."dna.fActionSave after save fCriteria="..tostring(dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].fCriteria)) end if ( not dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].fCriteria ) then -- We have a syntax problem dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].strSyntax = L["action/_dna_syntax_status/e1"]..":"..ret1 print(L["utils/debug/prefix"]..L["action/bCriteriaTest/loadstringerror"].." "..tostring(dna.D.RTMC[dna.ui.STL[2]].text)..":"..tostring(dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].text)) else dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].strSyntax = nil end end --***************************************************** --Action Panel --***************************************************** function dna.ui:CAP(ActionName)--CAP=Create Action Panel dna.ui.DB = {} dna.ui.sgMain.tgMain:RefreshTree() -- Gets rid of the rotation from the tree dna.ui.sgMain.tgMain.sgPanel:ReleaseChildren() -- clears the right panel dna.ui.SelectRotation(dna.DB.global.treeMain[dna.ui.STL[1]].children[dna.ui.STL[2]].text, true) -- Select the rotation first dna.ui.DB = dna.DB.global.treeMain[dna.ui.STL[1]].children[dna.ui.STL[2]].children[dna.ui.STL[3]] dna.ui.sgMain.tgMain.sgPanel:ResumeLayout() -- Pause or resume the righ tsgPanel fill layout if you need it or not -- Criteria tree goes in the sgPanel dna.ui.sgMain.tgMain.sgPanel.tgCriteria = dna.lib_acegui:Create("TreeGroup") dna.ui.sgMain.tgMain.sgPanel:AddChild( dna.ui.sgMain.tgMain.sgPanel.tgCriteria ) dna.ui.sgMain.tgMain.sgPanel.tgCriteria:SetTree( dna.D.criteriatree ) dna.ui.sgMain.tgMain.sgPanel:SetHeight(315) dna.ui.sgMain.tgMain.sgPanel.tgCriteria:SetTreeWidth( 350, true ) -- This is the left side width with the categories dna.ui.sgMain.tgMain.sgPanel.tgCriteria:SetFullWidth(true) dna.ui.sgMain.tgMain.sgPanel.tgCriteria:SetCallback( "OnGroupSelected", dna.ui.tgCriteriaOnGroupSelected ) -- Create the criteria panel dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel = dna.lib_acegui:Create("SimpleGroup") dna.ui.sgMain.tgMain.sgPanel.tgCriteria:AddChild(dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel) dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:SetLayout("List") dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:SetFullWidth(true) dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:SetWidth(100) -- The criteria edit box dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.mlebCriteria = dna.lib_acegui:Create( "MultiLineEditBox" ) local mlebCriteria = dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.mlebCriteria dna.ui.sgMain.tgMain.sgPanel:AddChild( mlebCriteria ) mlebCriteria:SetLabel( L["action/mlebCriteria/l"] ) mlebCriteria:SetHeight(250) mlebCriteria:SetWidth(480) mlebCriteria:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.tgCriteria.frame, "BOTTOMLEFT", 20, 0) mlebCriteria:SetCallback( "OnEnterPressed" , function(self) dna.ui.DB.criteria = self:GetText() dna.fActionSave() end ) mlebCriteria.editBox:SetScript("OnMouseUp",function(self, button) dna.ui.fMain:SetStatusText( '' ) local Text, Cursor = self:GetText(), self:GetCursorPosition() self:Insert( "" ) -- Delete selected text local TextNew, CursorNew = self:GetText(), self:GetCursorPosition() self:SetText( Text ) --Restore previous text self:SetCursorPosition( Cursor ) local Start, End = CursorNew, #Text - ( #TextNew - CursorNew ) self:HighlightText( Start, End ) local lHighlightedText = tostring(string.sub(self:GetText(), (Start+1), End)) local spellLink = GetSpellLink( lHighlightedText ) if ( spellLink ) then print(L["utils/debug/prefix"]..spellLink) dna.ui.fMain:SetStatusText( spellLink ) elseif ( select(2, GetItemInfo( lHighlightedText ) ) ) then print(L["utils/debug/prefix"]..select(2, GetItemInfo( lHighlightedText ) ) ) dna.ui.fMain:SetStatusText( select(2, GetItemInfo( lHighlightedText ) ) ) end end ) mlebCriteria:SetText( dna.ui.DB.criteria or "") -- The Line Numbers label -- https://www.wowace.com/projects/ace3/pages/ace-gui-3-0-widgets#title-2-10 dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.labelLineNumbers = dna.lib_acegui:Create("Label") local labelLineNumbers = dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.labelLineNumbers dna.ui.sgMain.tgMain.sgPanel:AddChild( labelLineNumbers ) labelLineNumbers:SetText( L["action/labelLineNumbers/l"] ) labelLineNumbers:SetHeight(250) labelLineNumbers:SetWidth(20) --labelLineNumbers:SetFont("Fonts\\FRIZQT__.TTF", 14) labelLineNumbers:SetFontObject(ChatFontNormal) labelLineNumbers:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.tgCriteria.frame, "BOTTOMLEFT", 0, -20) -- And button local bCriteriaAnd = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel:AddChild( bCriteriaAnd ) bCriteriaAnd:SetText( L["action/bCriteriaAnd/l"] ) bCriteriaAnd:SetWidth(85) bCriteriaAnd:SetPoint("TOPLEFT", mlebCriteria.frame, "BOTTOMLEFT", 65, 27); bCriteriaAnd:SetCallback( "OnClick", function() dna.ui.DB.criteria=mlebCriteria:GetText().." and \n" mlebCriteria:SetText( dna.ui.DB.criteria ) dna.fActionSave() end ) -- Or button local bCriteriaOr = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel:AddChild( bCriteriaOr ) bCriteriaOr:SetText( L["action/bCriteriaOr/l"] ) bCriteriaOr:SetWidth(85) bCriteriaOr:SetPoint("TOPLEFT", bCriteriaAnd.frame, "TOPRIGHT", 0, 0); bCriteriaOr:SetCallback( "OnClick", function() dna.ui.DB.criteria=mlebCriteria:GetText().." or " mlebCriteria:SetText( dna.ui.DB.criteria ) dna.fActionSave() end ) -- Not button local bCriteriaNot = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel:AddChild( bCriteriaNot ) bCriteriaNot:SetText( L["action/bCriteriaNot/l"] ) bCriteriaNot:SetWidth(85) bCriteriaNot:SetPoint("TOPLEFT", bCriteriaOr.frame, "TOPRIGHT", 0, 0); bCriteriaNot:SetCallback( "OnClick", function() dna.ui.DB.criteria=mlebCriteria:GetText().." not " mlebCriteria:SetText( dna.ui.DB.criteria ) dna.fActionSave() end ) -- Clear button local bCriteriaClear = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel:AddChild( bCriteriaClear ) bCriteriaClear:SetText( L["common/clear"] ) bCriteriaClear:SetWidth(85) bCriteriaClear:SetPoint("TOPLEFT", bCriteriaNot.frame, "TOPRIGHT", 0, 0); bCriteriaClear:SetCallback( "OnClick", function() dna.ui.DB.criteria="" mlebCriteria:SetText( dna.ui.DB.criteria ) dna.fActionSave() end ) -- Information MultiLineEditBox where we display debug information dna.ui.sgMain.tgMain.sgPanel.mlebInfo = dna.lib_acegui:Create( "MultiLineEditBox" ) dna.ui.sgMain.tgMain.sgPanel:AddChild( dna.ui.sgMain.tgMain.sgPanel.mlebInfo ) local mlebInfo = dna.ui.sgMain.tgMain.sgPanel.mlebInfo mlebInfo:SetNumLines(22) mlebInfo:SetWidth(500) mlebInfo:SetLabel("") mlebInfo:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.frame, "TOPLEFT", 0, 5) mlebInfo:SetText( "" ) mlebInfo:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/mlebInfo/tt"], "TOPRIGHT", "TOPLEFT", 0, 0, "text") dna.bPauseDebugDisplay = true end ) mlebInfo:SetCallback( "OnLeave", function() dna.ui.HideTooltip(); dna.bPauseDebugDisplay = false end ) mlebInfo:DisableButton( true ) mlebInfo.frame:Hide() -- Debug Information CheckBox dna.ui.sgMain.tgMain.sgPanel.cbInfo = dna.lib_acegui:Create("CheckBox") dna.ui.sgMain.tgMain.sgPanel:AddChild( dna.ui.sgMain.tgMain.sgPanel.cbInfo ) local cbInfo = dna.ui.sgMain.tgMain.sgPanel.cbInfo cbInfo:SetWidth(20) cbInfo.Tooltip=nil cbInfo:SetPoint("TOPRIGHT", mlebCriteria.frame, "BOTTOMRIGHT", -20, 25); cbInfo:SetImage("Interface\\FriendsFrame\\InformationIcon") cbInfo:SetLabel( "" ) cbInfo:SetCallback( "OnValueChanged", function(self) if ( self:GetValue() == true ) then dna.ui.sgMain.tgMain.sgPanel.tgCriteria.frame:Hide() mlebInfo.frame:Show() else dna.ui.sgMain.tgMain.sgPanel.mlebInfo.frame._dna_sabframe = nil dna.ui.sgMain.tgMain.sgPanel.tgCriteria.frame:Show() mlebInfo.frame:Hide() end end ) cbInfo:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/cbInfo/tt"], "BOTTOM", "TOP", 0, 0, "text") end ) cbInfo:SetCallback( "OnLeave", function() dna.ui.HideTooltip() end ) -- Move up Action interactive label local ilAMoveUp = dna.lib_acegui:Create("InteractiveLabel") dna.ui.sgMain.tgMain.sgPanel:AddChild( ilAMoveUp ) ilAMoveUp:SetWidth(40);ilAMoveUp:SetHeight(40) ilAMoveUp:SetImage("Interface\\MINIMAP\\UI-Minimap-MinimizeButtonUp-Up") ilAMoveUp:SetImageSize(40, 40) ilAMoveUp:SetHighlight("Interface\\MINIMAP\\UI-Minimap-MinimizeButtonUp-Highlight") ilAMoveUp:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.frame, "TOPLEFT", -7, -560); ilAMoveUp:SetCallback( "OnClick", function() dna.ui.bMoveAction(-1) end ) ilAMoveUp:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/ilAMoveUp/tt"], "LEFT", "RIGHT", 0, 0, "text") end ) ilAMoveUp:SetCallback( "OnLeave", function() dna.ui.HideTooltip() end ) -- Move down Action interactive label local ilAMoveDown = dna.lib_acegui:Create("InteractiveLabel") dna.ui.sgMain.tgMain.sgPanel:AddChild( ilAMoveDown ) ilAMoveDown:SetWidth(40);ilAMoveDown:SetHeight(40) ilAMoveDown:SetImage("Interface\\MINIMAP\\UI-Minimap-MinimizeButtonDown-Up") ilAMoveDown:SetImageSize(40, 40) ilAMoveDown:SetHighlight("Interface\\MINIMAP\\UI-Minimap-MinimizeButtonDown-Highlight") ilAMoveDown:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.frame, "TOPLEFT", -7, -585); ilAMoveDown:SetCallback( "OnClick", function() dna.ui.bMoveAction(1) end ) ilAMoveDown:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/ilAMoveDown/tt"], "LEFT", "RIGHT", 0, 0, "text") end ) ilAMoveDown:SetCallback( "OnLeave", function() dna.ui.HideTooltip() end ) -- Keybind -- local bActionKeybind = dna.lib_acegui:Create("Keybinding") -- dna.ui.sgMain.tgMain.sgPanel:AddChild( bActionKeybind ) -- bActionKeybind:SetWidth(100) -- bActionKeybind:SetLabel(L["common/hotkey/l"]) -- bActionKeybind:SetPoint("TOPLEFT", ilAMoveDown.frame, "TOPRIGHT", 0, 10); -- bActionKeybind:SetCallback( "OnKeyChanged", function(self) -- if ( InCombatLockdown() ) then dna.ui.fMain:SetStatusText( L["common/error/keybindincombat"] ) end -- dna.ui.DB.hk = self:GetKey(); -- dna.AButtons.bInitComplete = false; -- self:SetKey( dna.ui.DB.hk or L["action/bActionKeybind/blizzard"]) -- end ) -- bActionKeybind:SetKey( dna.ui.DB.hk or L["action/bActionKeybind/blizzard"] ) -- bActionKeybind.label:SetPoint("TOPLEFT", bActionKeybind.frame, "TOPLEFT", -40, 0); -- Delete Action button local bActionDelete = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel:AddChild( bActionDelete ) bActionDelete:SetWidth(100) bActionDelete:SetText(L["common/delete"]) bActionDelete:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.frame, "TOPLEFT", 40, -590); bActionDelete:SetCallback( "OnClick", dna.ui.bActionDeleteOnClick ) bActionDelete:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/bActionDelete/tt"], "LEFT", "RIGHT", 0, 0, "text") end ) bActionDelete:SetCallback( "OnLeave", function() dna.ui.HideTooltip() end ) -- Rename Action edit box local ebRenameAction = dna.lib_acegui:Create("EditBox") dna.ui.sgMain.tgMain.sgPanel:AddChild( ebRenameAction ) ebRenameAction:SetLabel( L["action/ebRenameAction/l"] ) ebRenameAction:SetWidth(160) ebRenameAction:SetPoint("TOPLEFT", dna.ui.sgMain.tgMain.sgPanel.frame, "TOPLEFT", 200, -570); ebRenameAction:SetCallback( "OnEnterPressed", dna.ui.ebRenameActionOnEnterPressed ) ebRenameAction:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, L["action/ebRenameAction/tt"], "BOTTOMRIGHT", "TOPRIGHT", 0, -10, "text") end ) ebRenameAction:SetCallback( "OnLeave", function() dna.ui.HideTooltip() end ) ebRenameAction:SetText( dna.ui.DB.text ) end --Action Panel Callbacks------------------------------- function dna.CreateCriteriaPanel(...) local args = {...} if ( not dna.ui.sgMain.tgMain.sgPanel.tgCriteria ) then return end for argi=1,dna.D.criteria[args[1]].a do --Build the criteria options based on dna.D.criteria dna.ui["ebArg"..argi] = dna.lib_acegui:Create("EditBox") dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:AddChild( dna.ui["ebArg"..argi] ) dna.ui["ebArg"..argi]:SetFullWidth(true) dna.ui["ebArg"..argi]:SetLabel( dna.D.criteria[args[1]]["a"..argi.."l"] or L["action/ebArg/l"]..argi ) dna.ui["ebArg"..argi]:SetText( dna.D.criteria[args[1]]["a"..argi.."dv"] or "" ) dna.ui["ebArg"..argi]:SetCallback( "OnEnter", function(self) dna.ui.ShowTooltip(self.frame, dna.D.criteria[args[1]]["a"..argi.."tt"], "BOTTOMLEFT", "TOPRIGHT", 0, 0, "text") end ) dna.ui["ebArg"..argi]:SetCallback( "OnLeave", dna.ui.HideTooltip ) dna.ui["ebArg"..argi]:DisableButton(true) end -- Add Criteria button local bCriteriaAdd = dna.lib_acegui:Create("Button") dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:AddChild( bCriteriaAdd ) bCriteriaAdd:SetText( L["action/bCriteriaAdd/l"] ) bCriteriaAdd:SetFullWidth(true) bCriteriaAdd:SetPoint("BOTTOMRIGHT", dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.frame, "BOTTOMRIGHT", 0, 0); bCriteriaAdd:SetCallback( "OnClick", function() dna.ui.CriteriaAddOnClick(args[1]) end ) end function dna.ui.CriteriaAddOnClick(criteriakey) local lCriteria = dna.D.criteria[criteriakey].f() or "" dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.mlebCriteria:SetText( (dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.mlebCriteria:GetText() or "")..lCriteria ) dna.ui.DB.criteria = (dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel.mlebCriteria:GetText() or "") dna.fActionSave() -- dna.AButtons.bInitComplete = false -- Criteria Add was clicked need initialization to create new criteria function end function dna.ui.tgCriteriaOnGroupSelected(...) local args = {...} args[1]:RefreshTree() --Refresh the tree so .selected gets updated dna.ui.sgMain.tgMain.sgPanel.tgCriteria.sgCriteriaPanel:ReleaseChildren() --Clears the right panel in the criteria tree dna.ui.SelectedCriteriaTreeButton=nil --Save the selected criteria for global scope for k,v in pairs(args[1].buttons) do if ( v.selected ) then dna.ui.SelectedCriteriaTreeButton = v end end if( not dna.ui.SelectedCriteriaTreeButton ) then --dna:dprint("Error: tgCriteriaOnGroupSelected called without a button selection") else local func, errorMessage = loadstring(dna.ui.SelectedCriteriaTreeButton.value) -- Use the .value field to create a function specific to the button if( not func ) then dna:dprint("Error: tgCriteriaOnGroupSelected loadingstring:"..dna.ui.SelectedCriteriaTreeButton.value.." Error:"..errorMessage) return end local success, errorMessage = pcall(func); -- Call the button specific function we loaded if( not success ) then print(L["utils/debug/prefix"].."Error criteria pcall:"..errorMessage) end end end function dna.ui.mlebActionTypeAttOnTextChanged(...) local args = {...} if ( not dna.IsBlank( args[1] ) and args[1]=="spell" ) then local spellID = dna.GetSpellID( args[3] ) dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link:SetText( (GetSpellLink( spellID ) or "")..' '..(spellID or "") ) dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link.Tooltip = GetSpellLink( spellID ) end if ( not dna.IsBlank( args[1] ) and args[1]=="macrotext" ) then local spellID = dna.GetSpellID( dna.ui:GetMacrotextTooltip( args[2] ) ) dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link:SetText( (GetSpellLink( spellID ) or "")..' '..(spellID or "") ) dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link.Tooltip = GetSpellLink( spellID ) end if ( not dna.IsBlank( args[1] ) and args[1]=="item" ) then local itemID = dna.GetItemId( args[2] ) if ( itemID ) then dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link:SetText( (select(2,GetItemInfo( itemID )) or "")..' '..(itemID or "") ) dna.ui.sgMain.tgMain.sgPanel.ilAtt2Link.Tooltip = select(2,GetItemInfo( itemID )) end end end function dna.ui.SetMultiActionValue( key, value) for atk, action in pairs( dna.D.RTMC[dna.ui.STL[2]].children ) do action[key] = value end end function dna.ui.bActionDeleteOnClick(...) if ( InCombatLockdown() ) then dna.ui.fMain:SetStatusText( L["common/error/deleteincombat"] ) return end dna.ui.fMain:SetStatusText( '' ) local deleteAKey = dna.ui.STL[3] dna.ui.sgMain.tgMain:SelectByValue(dna.D.RTM.value.."\001"..dna.D.RTMC[dna.ui.STL[2]].value) -- Select parent tree before deleting so table does not get messed up tremove(dna.D.RTMC[dna.ui.STL[2]].children, deleteAKey) dna.ui.sgMain.tgMain:RefreshTree() -- Gets rid of the action from the tree dna.ui.sgMain.tgMain.sgPanel:ReleaseChildren() -- clears the right panel dna.ui.sgMain.tgMain:SelectByValue(dna.D.RTM.value.."\001"..dna.D.RTMC[dna.ui.STL[2]].value) end function dna.ui.bMoveAction(movevalue) if ( InCombatLockdown() ) then dna.ui.fMain:SetStatusText( L["common/error/priorityincombat"] ) return end local SavedAction = dna:CopyTable(dna.ui.DB) -- Deepcopy the action from the db local maxKey = #(dna.D.RTMC[dna.ui.STL[2]].children) tremove(dna.D.RTMC[dna.ui.STL[2]].children, dna.ui.STL[3]) dna.ui.sgMain.tgMain:RefreshTree() -- Gets rid of the action from the tree dna.ui.sgMain.tgMain.sgPanel:ReleaseChildren() -- clears the right panel dna.ui.STL[3] = dna.ui.STL[3]+movevalue -- Now change the key value to up or down if ( dna.ui.STL[3] < 1) then dna.ui.STL[3] = 1 end if ( dna.ui.STL[3] > maxKey ) then dna.ui.STL[3] = maxKey end tinsert(dna.D.RTMC[dna.ui.STL[2]].children, (dna.ui.STL[3]), SavedAction) dna.ui.sgMain.tgMain:SelectByValue(dna.D.RTM.value.."\001"..dna.D.RTMC[dna.ui.STL[2]].value.."\001"..dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].value) end function dna.ui.ebRenameActionOnEnterPressed(...) local args = {...} if ( dna.ui.EntryHasErrors( args[3] ) ) then dna.ui.fMain:SetStatusText( string.format(L["common/error/unsafestring"], args[3]) ) return end local NewActionText = args[3] local NewActionValue = 'dna.ui:CAP([=['..NewActionText..']=])' if ( dna:SearchTable(dna.D.RTMC[dna.ui.STL[2]].children, "text", NewActionText) ) then dna.ui.fMain:SetStatusText( string.format(L["common/error/exists"], NewActionText) ) else dna.ui.fMain:SetStatusText( "" ) -- Clear any previous errors dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].text = NewActionText dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].value = NewActionValue dna.ui.sgMain.tgMain:RefreshTree() -- Refresh the tree dna.ui.sgMain.tgMain:SelectByValue(dna.D.RTM.value.."\001"..dna.D.RTMC[dna.ui.STL[2]].value.."\001"..dna.D.RTMC[dna.ui.STL[2]].children[dna.ui.STL[3]].value) end end
local ffi = require 'ffi' local uni = require 'ffi.unicode' ffi.cdef[[ int MessageBoxW(unsigned int hWnd, const wchar_t* lpText, const wchar_t* lpCaption, unsigned int uType); ]] local MB_ICONQUESTION = 0x00000020 local MB_OK = 0x00000000 local function messagebox(hwnd, text, caption, type) local wtext = uni.u2w(text) local wcaption = uni.u2w(caption) return ffi.C.MessageBoxW(hwnd, wtext, wcaption, type) end return function(caption, fmt, ...) return messagebox(0, fmt:format(...), caption, MB_ICONQUESTION | MB_OK) end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Gimbal" ENT.WireDebugName = "Gimbal" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:GetPhysicsObject():EnableGravity(false) self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]"}) self.XYZ = Vector() end function ENT:TriggerInput(name,value) if name == "On" then self.On = value ~= 0 else self.TargetPos = nil self.TargetDir = nil self.TargetAng = nil if name == "X" then self.XYZ.x = value self.TargetPos = self.XYZ elseif name == "Y" then self.XYZ.y = value self.TargetPos = self.XYZ elseif name == "Z" then self.XYZ.z = value self.TargetPos = self.XYZ elseif name == "Target" then self.XYZ = Vector(value.x, value.y, value.z) self.TargetPos = self.XYZ elseif name == "Direction" then self.TargetDir = value elseif name == "Angle" then self.TargetAng = value end end self:ShowOutput() return true end function ENT:Think() if self.On then local ang if self.TargetPos then ang = (self.TargetPos - self:GetPos()):Angle() elseif self.TargetDir then ang = self.TargetDir:Angle() elseif self.TargetAng then ang = self.TargetAng end if ang then self:SetAngles(ang + Angle(90,0,0)) end -- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions self:GetPhysicsObject():Wake() end self:NextThink(CurTime()) return true end function ENT:ShowOutput() if not self.On then self:SetOverlayText("Off") elseif self.TargetPos then self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z)) elseif self.TargetDir then self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z)) elseif self.TargetAng then self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll)) end end duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
---@meta ---@class ccs.ActionTimeline :cc.Action@all parent class: Action,PlayableProtocol local ActionTimeline={ } ccs.ActionTimeline=ActionTimeline ---* ---@return self function ActionTimeline:clearFrameEndCallFuncs () end ---* add a frame end call back to animation's end frame<br> ---* param animationName @addFrameEndCallFunc, make the animationName as funcKey<br> ---* param func the callback function ---@param animationName string ---@param func function ---@return self function ActionTimeline:setAnimationEndCallFunc (animationName,func) end ---* add Timeline to ActionTimeline ---@param timeline ccs.Timeline ---@return self function ActionTimeline:addTimeline (timeline) end ---* Get current frame. ---@return int function ActionTimeline:getCurrentFrame () end ---* Start frame index of this action ---@return int function ActionTimeline:getStartFrame () end ---* Pause the animation. ---@return self function ActionTimeline:pause () end ---* / @{/ @name implement Playable Protocol ---@return self function ActionTimeline:start () end ---* ---@return boolean function ActionTimeline:init () end ---* ---@param timeline ccs.Timeline ---@return self function ActionTimeline:removeTimeline (timeline) end ---* ---@return self function ActionTimeline:clearFrameEventCallFunc () end ---* Last frame callback will call when arriving last frame ---@param listener function ---@return self function ActionTimeline:setLastFrameCallFunc (listener) end ---* ---@return array_table function ActionTimeline:getTimelines () end ---* ---@param animationName string ---@param loop boolean ---@return self function ActionTimeline:play (animationName,loop) end ---* ---@param animationName string ---@return ccs.AnimationInfo function ActionTimeline:getAnimationInfo (animationName) end ---* Resume the animation. ---@return self function ActionTimeline:resume () end ---* add a callback function after played frameIndex<br> ---* param frameIndex the frame index call back after<br> ---* param funcKey for identity the callback function<br> ---* param func the callback function ---@param frameIndex int ---@param funcKey string ---@param func function ---@return self function ActionTimeline:addFrameEndCallFunc (frameIndex,funcKey,func) end ---* ---@param animationName string ---@return self function ActionTimeline:removeAnimationInfo (animationName) end ---* Get current animation speed. ---@return float function ActionTimeline:getTimeSpeed () end ---* AnimationInfo ---@param animationInfo ccs.AnimationInfo ---@return self function ActionTimeline:addAnimationInfo (animationInfo) end ---* ---@return int function ActionTimeline:getDuration () end ---* Goto the specified frame index, and pause at this index.<br> ---* param startIndex The animation will pause at this index. ---@param startIndex int ---@return self function ActionTimeline:gotoFrameAndPause (startIndex) end ---* Whether or not Action is playing. ---@return boolean function ActionTimeline:isPlaying () end ---* ---@param frameIndex int ---@return self function ActionTimeline:removeFrameEndCallFuncs (frameIndex) end ---@overload fun(int:int,int1:boolean):self ---@overload fun(int:int):self ---@overload fun(int:int,int:int,int2:boolean):self ---@overload fun(int:int,int:int,int:int,boolean:boolean):self ---@param startIndex int ---@param endIndex int ---@param currentFrameIndex int ---@param loop boolean ---@return self function ActionTimeline:gotoFrameAndPlay (startIndex,endIndex,currentFrameIndex,loop) end ---* ---@param animationName string ---@return boolean function ActionTimeline:IsAnimationInfoExists (animationName) end ---* End frame of this action.<br> ---* When action play to this frame, if action is not loop, then it will stop, <br> ---* or it will play from start frame again. ---@return int function ActionTimeline:getEndFrame () end ---* Set the animation speed, this will speed up or slow down the speed. ---@param speed float ---@return self function ActionTimeline:setTimeSpeed (speed) end ---* ---@return self function ActionTimeline:clearLastFrameCallFunc () end ---* duration of the whole action ---@param duration int ---@return self function ActionTimeline:setDuration (duration) end ---* Set current frame index, this will cause action plays to this frame. ---@param frameIndex int ---@return self function ActionTimeline:setCurrentFrame (frameIndex) end ---* ---@param frameIndex int ---@param funcKey string ---@return self function ActionTimeline:removeFrameEndCallFunc (frameIndex,funcKey) end ---* ---@return self function ActionTimeline:create () end ---* ---@param target cc.Node ---@return self function ActionTimeline:startWithTarget (target) end ---* Returns a reverse of ActionTimeline. <br> ---* Not implement yet. ---@return self function ActionTimeline:reverse () end ---* Returns a clone of ActionTimeline ---@return self function ActionTimeline:clone () end ---* ---@return self function ActionTimeline:stop () end ---* ---@param delta float ---@return self function ActionTimeline:step (delta) end ---* ---@return boolean function ActionTimeline:isDone () end ---* ---@return self function ActionTimeline:ActionTimeline () end
function onSay(cid, words, param, channel) doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have " .. getPlayerMoney(cid) .. " gold.") return true end
--[[ minted -- enable the minted environment for code listings in beamer and latex. MIT License Copyright (c) 2019 Stephen McDowell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------------------------------------------------------- -- Quick documentation. See full documentation here: -- -- https://github.com/pandoc/lua-filters/blob/master/minted -- -------------------------------------------------------------------------------- --[[ Brief overview of metadata keys that you can use in your document: minted: no_default_autogobble: <boolean>, *DISCOURAGED* no_mintinline: <boolean> default_block_language: <string> default_inline_language: <string> block_attributes: <list of strings> - attr_1 - attr_2 - ... inline_attributes: <list of strings> - attr_1 - attr_2 - ... In words, underneath the `minted` metadata key, you have the following options: ### `no_default_autogobble` (boolean) By default this filter will always use `autogobble` with minted, which will automatically trim common preceding whitespace. This is important because code blocks nested under a list or other block elements _will_ have common preceding whitespace that you _will_ want trimmed. ### `no_mintinline` (boolean) Globally prevent this filter from emitting `\mintinline` calls for inline Code elements, emitting `\texttt` instead. Possibly useful in saving compile time for large documents that do not seek to have syntax highlighting on inline code elements. ### `default_block_language` (string) The default pygments lexer class to use for code blocks. By default this is `"text"`, meaning no syntax highlighting. This is a fallback value, code blocks that explicitly specify a lexer will not use it. ### `default_inline_language` (string) Same as `default_block_language`, only for inline code (typed in single backticks). The default is also `"text"`, and changing is discouraged. ### `block_attributes` (list of strings) Any default attributes to apply to _all_ code blocks. These may be overriden on a per-code-block basis. See section 5.3 of the [minted documentation][minted_docs] for available options. ### `inline_attributes` (list of strings) Any default attributes to apply to _all_ inline code. These may be overriden on a per-code basis. See section 5.3 of the [minted documentation][minted_docs] for available options. [minted_docs]: http://mirrors.ctan.org/macros/latex/contrib/minted/minted.pdf ]] local List = require('pandoc.List') -------------------------------------------------------------------------------- -- Potential metadata elements to override. -- -------------------------------------------------------------------------------- local minted_no_mintinline = false local minted_default_block_language = "text" local minted_default_inline_language = "text" local minted_block_attributes = {} local minted_inline_attributes = {} -------------------------------------------------------------------------------- -- Constants used to differentiate Code and CodeBlock elements. -- -------------------------------------------------------------------------------- local MintedInline = 0 local MintedBlock = 1 -------------------------------------------------------------------------------- -- Utility functions. -- -------------------------------------------------------------------------------- -- Return the string lexer class to be used with minted. `elem` should be -- either a Code or CodeBlock element (whose `classes` list will be inspected -- first). `kind` is assumed to be either `MintedInline` or `MintedBlock` in -- order to choose the appropriate fallback lexer when unspecified. local function minted_language(elem, kind) -- If the code [block] attached classes, we assume the first one is the -- lexer class to use. if #elem.classes > 0 then return elem.classes[1] end -- Allow user-level metadata to override the inline language. if kind == MintedInline then return minted_default_inline_language end -- Allow user-level metadata to override the block language. if kind == MintedBlock then return minted_default_block_language end -- Failsafe, should not hit here unless function called incorrectly. return "text" end -- Returns a boolean specifying whether or not the specified string `cls` is an -- option that is supported by the minted package. local function is_minted_class(cls) -- Section 5.3 Available Options of Minted documentation. Note that many of -- these do not apply to \mintinline (inline Code). Users are responsible -- for supplying valid arguments to minted. For example, specifying -- `autogobble` and `gobble` at the same time is a usage error. -- -- http://mirrors.ctan.org/macros/latex/contrib/minted/minted.pdf local all_minted_options = List:new{ "autogobble", "baselinestretch", "beameroverlays", "breakafter", "breakaftergroup", "breakaftersymbolpre", "breakaftersymbolpost", "breakanywhere", "breakanywheresymbolpre", "breakanywheresymbolpost", "breakautoindent", "breakbefore", "breakbeforegroup", "breakbeforesymbolpre", "breakbeforesymbolpost", "breakbytoken", "breakbytokenanywhere", "breakindent", "breakindentnchars", "breaklines", "breaksymbol", "breaksymbolleft", "breaksymbolright", "breaksymbolindent", "breaksymbolindentnchars", "breaksymbolindentleft", "breaksymbolindentleftnchars", "breaksymbolindentright", "breaksymbolindentrightnchars", "breaksymbolsep", "breaksymbolsepnchars", "breaksymbolsepleft", "breaksymbolsepleftnchars", "breaksymbolsepright", "breaksymbolseprightnchars", "bgcolor", "codetagify", "curlyquotes", "encoding", "escapeinside", "firstline", "firstnumber", "fontfamily", "fontseries", "fontsize", "fontshape", "formatcom", "frame", "framerule", "framesep", "funcnamehighlighting", "gobble", "highlightcolor", "highlightlines", "keywordcase", "label", "labelposition", "lastline", "linenos", "numberfirstline", "numbers", "mathescape", "numberblanklines", "numbersep", "obeytabs", "outencoding", "python3", "resetmargins", "rulecolor", "samepage", "showspaces", "showtabs", "space", "spacecolor", "startinline", "style", "stepnumber", "stepnumberfromfirst", "stepnumberoffsetvalues", "stripall", "stripnl", "tab", "tabcolor", "tabsize", "texcl", "texcomments", "xleftmargin", "xrightmargin" } return all_minted_options:includes(cls, 0) end -- Return a string for the minted attributes `\begin{minted}[attributes]` or -- `\mintinline[attributes]`. Attributes are acquired by inspecting the -- specified element's `classes` and `attr` fields. Any global attributes -- provided in the document metadata will be included _only_ if they do not -- override the element-level attributes. -- -- `elem` should either be a Code or CodeBlock element, and `kind` is assumed to -- be either `MintedInline` or `MintedBlock`. The `kind` determines which -- global default attribute list to use. local function minted_attributes(elem, kind) -- The full listing of attributes that will be joined and returned. local minted_attributes = {} -- Book-keeping, track xxx=yyy keys `xxx` that have been added to -- `minted_attributes` to make checking optional global defaults via the -- `block_attributes` or `inline_attributes` easier. local minted_keys = {} -- Boolean style options for minted (e.g., ```{.bash .autogobble}) will appear -- in the list of classes. for _, cls in ipairs(elem.classes) do if is_minted_class(cls) then table.insert(minted_attributes, cls) table.insert(minted_keys, cls) end end -- Value options using key=value (e.g., ```{.bash fontsize=\scriptsize}) show -- up in the list of attributes. for cls, value in pairs(elem.attributes) do if is_minted_class(cls) then table.insert(minted_attributes, cls .. "=" .. value) table.insert(minted_keys, cls) end end -- Add any global defaults _only_ if they do not conflict. Note that conflict -- is only in the literal sense. If a user has `autogobble` and `gobble=2` -- specified, these do conflict in the minted sense, but this filter makes no -- checks on validity ;) local global_defaults = nil if kind == MintedInline then global_defaults = minted_inline_attributes elseif kind == MintedBlock then global_defaults = minted_block_attributes end for _, global_attr in ipairs(global_defaults) do -- Either use the index of `=` minus one, or -1 if no `=` present. Fallback -- on -1 means that the substring is the original string. local end_idx = (string.find(global_attr, "=") or 0) - 1 local global_key = string.sub(global_attr, 1, end_idx) local can_insert_global = true for _, existing_key in ipairs(minted_keys) do if existing_key == global_key then can_insert_global = false break end end if can_insert_global then table.insert(minted_attributes, global_attr) end end -- Return a comma delimited string for specifying the attributes to minted. return table.concat(minted_attributes, ",") end -- Return the specified `elem` with any minted data removed from the `classes` -- and `attr`. Otherwise writers such as the HTML writer might produce invalid -- code since latex makes heavy use of the \backslash. local function remove_minted_attibutes(elem) -- Remove any minted items from the classes. classes = {} for _, cls in ipairs(elem.classes) do if not is_minted_class(cls) and cls ~= "no_minted" then table.insert(classes, cls) end end elem.classes = classes -- Remove any minted items from the attributes. extra_attrs = {} for cls, value in pairs(elem.attributes) do if not is_minted_class(cls) then table.insert(extra_attrs, {cls, value}) end end elem.attributes = extra_attrs -- Return the (potentially modified) element for pandoc to take over. return elem end -- Return a `start_delim` and `end_delim` that can safely wrap around the -- specified `text` when used inline. If no special characters occur in `text`, -- then a pair of braces are returned. Otherwise, if any character of -- `possible_delims` are not in `text`, then it is returned. If no delimiter -- could be found, an error is raised. local function minted_inline_delims(text) local start_delim, end_delim if text:find('[{}]') then -- Try some other delimiter (the alphanumeric digits are in Python's -- string.digits + string.ascii_letters order) possible_delims = ('|!@#^&*-=+' .. '0123456789' .. 'abcdefghijklmnopqrstuvwxyz' .. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') for char in possible_delims:gmatch('.') do if not text:find(char, 1, true) then start_delim = char end_delim = char break end end if not start_delim then local msg = 'Unable to determine delimiter to use around inline code %q' error(msg:format(text)) end else start_delim = '{' end_delim = '}' end return start_delim, end_delim end -------------------------------------------------------------------------------- -- Pandoc overrides. -- -------------------------------------------------------------------------------- -- Override the pandoc Meta function so that we can parse the metadata for the -- document and store the necessary variables locally to use in other functions -- such as Code and CodeBlock (helper methods). function Meta(m) -- Grab the `minted` metadata, quit early if not present. local minted = m["minted"] local found_autogobble = false local always_autogobble = true if minted ~= nil then -- Parse and set the global bypass to turn off all \mintinline calls. local no_mintinline = minted["no_mintinline"] if no_mintinline ~= nil then minted_no_mintinline = no_mintinline end -- Parse and set the default block language. local default_block_language = minted.default_block_language and pandoc.utils.stringify(minted.default_block_language) if default_block_language ~= nil then minted_default_block_language = default_block_language end -- Parse and set the default inline language. local default_inline_language = minted.default_inline_language and pandoc.utils.stringify(minted.default_inline_language) if default_inline_language ~= nil then minted_default_inline_language = default_inline_language end -- Parse the global default minted attributes to use on every block. local block_attributes = minted["block_attributes"] if block_attributes ~= nil then for _, attr in ipairs(block_attributes) do if attr == "autogobble" then found_autogobble = true end table.insert(minted_block_attributes, attr[1].text) end end -- Allow users to turn off autogobble for blocks, but really they should not -- ever seek to do this (indented code blocks under list for example). local no_default_autogobble = minted["no_default_autogobble"] if no_default_autogobble ~= nil then always_autogobble = not no_default_autogobble end -- Parse the global default minted attributes to use on ever inline. local inline_attributes = minted["inline_attributes"] if inline_attributes ~= nil then for _, attr in ipairs(inline_attributes) do table.insert(minted_inline_attributes, attr[1].text) end end end -- Make sure autogobble is turned on by default if no `minted` meta key is -- provided for the document. if always_autogobble and not found_autogobble then table.insert(minted_block_attributes, "autogobble") end -- Return the metadata to pandoc (unchanged). return m end -- Override inline code elements to use \mintinline for beamer / latex writers. -- Other writers have all minted attributes removed. function Code(elem) if FORMAT == "beamer" or FORMAT == "latex" then -- Allow a bypass to turn off \mintinline via adding .no_minted class. local found_no_minted_class = false for _, cls in ipairs(elem.classes) do if cls == "no_minted" then found_no_minted_class = true break end end -- Check for local or global bypass to turn off \mintinline if minted_no_mintinline or found_no_minted_class then return nil -- Return `nil` signals to `pandoc` that elem is not changed. end local start_delim, end_delim = minted_inline_delims(elem.text) local language = minted_language(elem, MintedInline) local attributes = minted_attributes(elem, MintedInline) local raw_minted = string.format( "\\mintinline[%s]{%s}%s%s%s", attributes, language, start_delim, elem.text, end_delim ) -- NOTE: prior to pandoc commit 24a0d61, `beamer` cannot be used as the -- RawBlock format. Using `latex` should not cause any problems. return pandoc.RawInline("latex", raw_minted) else return remove_minted_attibutes(elem) end end -- Override code blocks to use \begin{minted}...\end{minted} for beamer / latex -- writers. Other writers have all minted attributes removed. function CodeBlock(block) if FORMAT == "beamer" or FORMAT == "latex" then local language = minted_language(block, MintedBlock) local attributes = minted_attributes(block, MintedBlock) local raw_minted = string.format( "\\begin{minted}[%s]{%s}\n%s\n\\end{minted}", attributes, language, block.text ) -- NOTE: prior to pandoc commit 24a0d61, `beamer` cannot be used as the -- RawBlock format. Using `latex` should not cause any problems. return pandoc.RawBlock("latex", raw_minted) else return remove_minted_attibutes(block) end end -- Override headers to make all beamer frames fragile, since any minted -- environments or \mintinline invocations will halt compilation if the frame -- is not marked as fragile. function Header(elem) if FORMAT == 'beamer' then -- Check first that 'fragile' is not already present. local has_fragile = false for _, val in ipairs(elem.classes) do if val == 'fragile' then has_fragile = true break end end -- If not found, add fragile to the list of classes. if not has_fragile then table.insert(elem.classes, 'fragile') end -- NOTE: pass the remaining work to pandoc, noting that 2.5 and below -- may duplicate the 'fragile' specifier. Duplicated fragile does *not* -- cause compile errors. return elem end end -- NOTE: order of return matters, Meta needs to be first otherwise the metadata -- from the document will not be loaded _first_. return { {Meta = Meta}, {Code = Code}, {CodeBlock = CodeBlock}, {Header = Header} }
if SERVER then AddCSLuaFile("shared.lua") end if CLIENT then SWEP.ViewModelFlip = true SWEP.PrintName = "P228 Compact" SWEP.IconLetter = "y" SWEP.Slot = 2 SWEP.Slotpos = 2 end SWEP.HoldType = "pistol" SWEP.Base = "rad_base" SWEP.ViewModel = "models/weapons/v_pist_p228.mdl" SWEP.WorldModel = "models/weapons/w_pist_p228.mdl" SWEP.SprintPos = Vector(-0.8052, 0, 3.0657) SWEP.SprintAng = Vector(-16.9413, -5.786, 4.0159) SWEP.IsSniper = false SWEP.AmmoType = "Pistol" SWEP.Primary.Sound = Sound( "Weapon_P228.Single" ) SWEP.Primary.Recoil = 5.5 SWEP.Primary.Damage = 25 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.035 SWEP.Primary.Delay = 0.150 SWEP.Primary.ClipSize = 12 SWEP.Primary.Automatic = false
--[[ Name: LibDeformat-3.0 Author(s): ckknight ([email protected]) Website: http://www.wowace.com/projects/libdeformat-3-0/ Description: A library to convert a post-formatted string back to its original arguments given its format string. License: MIT ]] local _, ADDONSELF = ... -- local MAJOR, MINOR = "ScrollingTable", tonumber("1637607028") or 40300; -- local lib, oldminor = LibStub:NewLibrary(MAJOR, MINOR); -- if not lib then -- return; -- Already loaded and no upgrade necessary. -- end ADDONSELF.deformat = {} local LibDeformat = ADDONSELF.deformat -- local LibDeformat = LibStub:NewLibrary("LibDeformat-3.0", 1) -- if not LibDeformat then -- return -- end -- this function does nothing and returns nothing local function do_nothing() end -- a dictionary of format to match entity local FORMAT_SEQUENCES = { ["s"] = ".+", ["c"] = ".", ["%d*d"] = "%%-?%%d+", ["[fg]"] = "%%-?%%d+%%.?%%d*", ["%%%.%d[fg]"] = "%%-?%%d+%%.?%%d*", } -- a set of format sequences that are string-based, i.e. not numbers. local STRING_BASED_SEQUENCES = { ["s"] = true, ["c"] = true, } local cache = setmetatable({}, {__mode='k'}) -- generate the deformat function for the pattern, or fetch from the cache. local function get_deformat_function(pattern) local func = cache[pattern] if func then return func end -- escape the pattern, so that string.match can use it properly local unpattern = '^' .. pattern:gsub("([%(%)%.%*%+%-%[%]%?%^%$%%])", "%%%1") .. '$' -- a dictionary of index-to-boolean representing whether the index is a number rather than a string. local number_indexes = {} -- (if the pattern is a numbered format,) a dictionary of index-to-real index. local index_translation = nil -- the highest found index, also the number of indexes found. local highest_index if not pattern:find("%%1%$") then -- not a numbered format local i = 0 while true do i = i + 1 local first_index local first_sequence for sequence in pairs(FORMAT_SEQUENCES) do local index = unpattern:find("%%%%" .. sequence) if index and (not first_index or index < first_index) then first_index = index first_sequence = sequence end end if not first_index then break end unpattern = unpattern:gsub("%%%%" .. first_sequence, "(" .. FORMAT_SEQUENCES[first_sequence] .. ")", 1) number_indexes[i] = not STRING_BASED_SEQUENCES[first_sequence] end highest_index = i - 1 else -- a numbered format local i = 0 while true do i = i + 1 local found_sequence for sequence in pairs(FORMAT_SEQUENCES) do if unpattern:find("%%%%" .. i .. "%%%$" .. sequence) then found_sequence = sequence break end end if not found_sequence then break end unpattern = unpattern:gsub("%%%%" .. i .. "%%%$" .. found_sequence, "(" .. FORMAT_SEQUENCES[found_sequence] .. ")", 1) number_indexes[i] = not STRING_BASED_SEQUENCES[found_sequence] end highest_index = i - 1 i = 0 index_translation = {} pattern:gsub("%%(%d)%$", function(w) i = i + 1 index_translation[i] = tonumber(w) end) end if highest_index == 0 then cache[pattern] = do_nothing else --[=[ -- resultant function looks something like this: local unpattern = ... return function(text) local a1, a2 = text:match(unpattern) if not a1 then return nil, nil end return a1+0, a2 end -- or if it were a numbered pattern, local unpattern = ... return function(text) local a2, a1 = text:match(unpattern) if not a1 then return nil, nil end return a1+0, a2 end ]=] local t = {} t[#t+1] = [=[ return function(text) local ]=] for i = 1, highest_index do if i ~= 1 then t[#t+1] = ", " end t[#t+1] = "a" if not index_translation then t[#t+1] = i else t[#t+1] = index_translation[i] end end t[#t+1] = [=[ = text:match(]=] t[#t+1] = ("%q"):format(unpattern) t[#t+1] = [=[) if not a1 then return ]=] for i = 1, highest_index do if i ~= 1 then t[#t+1] = ", " end t[#t+1] = "nil" end t[#t+1] = "\n" t[#t+1] = [=[ end ]=] t[#t+1] = "return " for i = 1, highest_index do if i ~= 1 then t[#t+1] = ", " end t[#t+1] = "a" t[#t+1] = i if number_indexes[i] then t[#t+1] = "+0" end end t[#t+1] = "\n" t[#t+1] = [=[ end ]=] t = table.concat(t, "") -- print(t) cache[pattern] = assert(loadstring(t))() end return cache[pattern] end --- Return the arguments of the given format string as found in the text. -- @param text The resultant formatted text. -- @param pattern The pattern used to create said text. -- @return a tuple of values, either strings or numbers, based on the pattern. -- @usage LibDeformat.Deformat("Hello, friend", "Hello, %s") == "friend" -- @usage LibDeformat.Deformat("Hello, friend", "Hello, %1$s") == "friend" -- @usage LibDeformat.Deformat("Cost: $100", "Cost: $%d") == 100 -- @usage LibDeformat.Deformat("Cost: $100", "Cost: $%1$d") == 100 -- @usage LibDeformat.Deformat("Alpha, Bravo", "%s, %s") => "Alpha", "Bravo" -- @usage LibDeformat.Deformat("Alpha, Bravo", "%1$s, %2$s") => "Alpha", "Bravo" -- @usage LibDeformat.Deformat("Alpha, Bravo", "%2$s, %1$s") => "Bravo", "Alpha" -- @usage LibDeformat.Deformat("Hello, friend", "Cost: $%d") == nil -- @usage LibDeformat("Hello, friend", "Hello, %s") == "friend" function LibDeformat.Deformat(text, pattern) if type(text) ~= "string" then error(("Argument #1 to `Deformat' must be a string, got %s (%s)."):format(type(text), text), 2) elseif type(pattern) ~= "string" then error(("Argument #2 to `Deformat' must be a string, got %s (%s)."):format(type(pattern), pattern), 2) end return get_deformat_function(pattern)(text) end --[===[@debug@ function LibDeformat.Test() local function tuple(success, ...) if success then return true, { n = select('#', ...), ... } else return false, ... end end local function check(text, pattern, ...) local success, results = tuple(pcall(LibDeformat.Deformat, text, pattern)) if not success then return false, results end if select('#', ...) ~= results.n then return false, ("Differing number of return values. Expected: %d. Actual: %d."):format(select('#', ...), results.n) end for i = 1, results.n do local expected = select(i, ...) local actual = results[i] if type(expected) ~= type(actual) then return false, ("Return #%d differs by type. Expected: %s (%s). Actual: %s (%s)"):format(type(expected), expected, type(actual), actual) elseif expected ~= actual then return false, ("Return #%d differs. Expected: %s. Actual: %s"):format(expected, actual) end end return true end local function test(text, pattern, ...) local success, problem = check(text, pattern, ...) if not success then print(("Problem with (%q, %q): %s"):format(text, pattern, problem or "")) end end test("Hello, friend", "Hello, %s", "friend") test("Hello, friend", "Hello, %1$s", "friend") test("Cost: $100", "Cost: $%d", 100) test("Cost: $100", "Cost: $%1$d", 100) test("Alpha, Bravo", "%s, %s", "Alpha", "Bravo") test("Alpha, Bravo", "%1$s, %2$s", "Alpha", "Bravo") test("Alpha, Bravo", "%2$s, %1$s", "Bravo", "Alpha") test("Alpha, Bravo, Charlie, Delta, Echo", "%s, %s, %s, %s, %s", "Alpha", "Bravo", "Charlie", "Delta", "Echo") test("Alpha, Bravo, Charlie, Delta, Echo", "%1$s, %2$s, %3$s, %4$s, %5$s", "Alpha", "Bravo", "Charlie", "Delta", "Echo") test("Alpha, Bravo, Charlie, Delta, Echo", "%5$s, %4$s, %3$s, %2$s, %1$s", "Echo", "Delta", "Charlie", "Bravo", "Alpha") test("Alpha, Bravo, Charlie, Delta, Echo", "%2$s, %3$s, %4$s, %5$s, %1$s", "Echo", "Alpha", "Bravo", "Charlie", "Delta") test("Alpha, Bravo, Charlie, Delta, Echo", "%3$s, %4$s, %5$s, %1$s, %2$s", "Delta", "Echo", "Alpha", "Bravo", "Charlie") test("Alpha, Bravo, Charlie, Delta", "%s, %s, %s, %s, %s", nil, nil, nil, nil, nil) test("Hello, friend", "Cost: $%d", nil) print("LibDeformat-3.0: Tests completed.") end --@end-debug@]===] setmetatable(LibDeformat, { __call = function(self, ...) return self.Deformat(...) end })
object_draft_schematic_dance_prop_prop_ribbon_spark_l_s02 = object_draft_schematic_dance_prop_shared_prop_ribbon_spark_l_s02:new { } ObjectTemplates:addTemplate(object_draft_schematic_dance_prop_prop_ribbon_spark_l_s02, "object/draft_schematic/dance_prop/prop_ribbon_spark_l_s02.iff")
local Com = require "meiru.com.com" ---------------------------------------------- --ComHeader ---------------------------------------------- local ComHeader = class("ComHeader", Com) function ComHeader:ctor() end local slower = string.lower function ComHeader:match(req, res) local header = {} -- log("req.rawheader =", req.rawheader) for k,v in pairs(req.rawheader) do k = slower(k) if k == 'user-agent' or k == 'content-type' then v = slower(v) end header[k] = v end req.header = header end return ComHeader
local HTTP = require("http") local Utils = require("utils") HTTP.create_server("0.0.0.0", 8080, function (req, res) local body = Utils.dump({req=req,headers=req.headers}) .. "\n" res:write_head(200, { ["Content-Type"] = "text/plain", ["Content-Length"] = #body }) res:finish(body) end) print("Server listening at http://localhost:8080/")
local recipe_infos = {} local long_pipes = { ["se-space-pipe-long-j-3" ] = "", ["se-space-pipe-long-j-5" ] = "", ["se-space-pipe-long-j-7" ] = "", ["se-space-pipe-long-s-9" ] = "", ["se-space-pipe-long-s-15"] = "", } local belt_colors = { "blue", "cyan", "green", "magenta", "red", "white", "yellow", } local transport_entities = { ["underground-belt"] = "underground-belt", ["transport-belt"] = "transport-belt", ["splitter"] = "splitter", } local always_recover = { ["se-space-pipe"] = true, ["se-deep-space-underground-belt-black"] = true, ["se-deep-space-transport-belt-black"] = true, ["se-deep-space-transport-belt-loader-black"] = true, ["se-deep-space-splitter-black"] = true, } local function is_base_entity(type, name) return type == "item" and always_recover[name] and true end for name, localized_name in pairs(long_pipes) do table.insert(recipe_infos, { recipe_name = name, entity_type = "storage-tank", -- yes, not "pipe" technology_name = "se-space-platform-scaffold", no_percentage_test = is_base_entity, }) end for _, color in pairs(belt_colors) do for name, type in pairs(transport_entities) do table.insert(recipe_infos, { recipe_name = "se-deep-space-".. name .."-".. color, entity_type = type, technology_name = "se-deep-space-transport-belt", no_percentage_test = is_base_entity, }) end end return function(processor_function) for _, recipe_info in pairs(recipe_infos) do processor_function(recipe_info) end end
-- -- Copyright 2012 Aaron MacDonald -- -- 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 Settings = {} ---------------------------------------------------------------------- local FILE = 'settings.txt' local DEFAULTS = {} DEFAULTS.volume = 1 DEFAULTS.key_north = 'w' DEFAULTS.key_east = 'd' DEFAULTS.key_south = 's' DEFAULTS.key_west = 'a' Settings.DEFAULTS = DEFAULTS local KEY_CONTROLS = { 'key_north', 'key_east', 'key_south', 'key_west' } Settings.KEY_CONTROLS = KEY_CONTROLS local current_settings = {} ---------------------------------------------------------------------- local function load() local write_defaults = not love.filesystem.exists(FILE) or not love.filesystem.isFile(FILE) local file = love.filesystem.newFile(FILE) if write_defaults then file:open('w') file:write( TSerial.pack(DEFAULTS) ) file:close() end file:open('r') current_settings = TSerial.unpack( file:read() ) file:close() for k, _ in pairs(DEFAULTS) do assert(current_settings[k] ~= nil) end end Settings.load = load local function save() assert(love.filesystem.exists(FILE)) assert(love.filesystem.isFile(FILE)) file = love.filesystem.newFile(FILE) file:open('w') file:write( TSerial.pack(current_settings) ) file:close() end ---------------------------------------------------------------------- local function get(key) assert(current_settings[key] ~= nil, 'Invalid setting: ' .. key) return current_settings[key] end Settings.get = get -- For printing keyboard controls local function get_key_control_name(key) assert(current_settings[key] ~= nil, 'Invalid setting: ' .. key) assert(string.find(key, 'key_'), 'Not a key control: ' .. key) local result = current_settings[key] if result == ' ' then result = 'space' end return result end Settings.get_key_control_name = get_key_control_name local function set(key, value) assert(current_settings[key] ~= nil, 'Invalid setting: ' .. key) assert(value ~= nil) current_settings[key] = value save() end Settings.set = set local function is_mute() local volume = get('volume') if volume == 0 then return true else return false end end Settings.is_mute = is_mute ---------------------------------------------------------------------- return Settings
CommandConst = { EnterState = 'EnterState', CloseWindow = 'CloseWindow', FormationChanged = 'FormationChanged', WindowCBackToB = 'WindowCBackToB', AdjustHeadView = 'AdjustHeadView', }
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Chemioue -- Type: NPC Quest -- !pos 82.041 -34.964 67.636 26 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) player:startEvent(280) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
local cauldron, sounds = {}, {} local S = minetest.get_translator("xdecor") -- Add more ingredients here that make a soup. local ingredients_list = { "apple", "mushroom", "honey", "pumpkin", "egg", "bread", "meat", "chicken", "carrot", "potato", "melon", "rhubarb", "cucumber", "corn", "beans", "berries", "grapes", "tomato", "wheat" } cauldron.cbox = { {0, 0, 0, 16, 16, 0}, {0, 0, 16, 16, 16, 0}, {0, 0, 0, 0, 16, 16}, {16, 0, 0, 0, 16, 16}, {0, 0, 0, 16, 8, 16} } function cauldron.stop_sound(pos) local spos = minetest.hash_node_position(pos) if sounds[spos] then minetest.sound_stop(sounds[spos]) end end function cauldron.idle_construct(pos) local timer = minetest.get_node_timer(pos) timer:start(10.0) cauldron.stop_sound(pos) end function cauldron.boiling_construct(pos) local spos = minetest.hash_node_position(pos) sounds[spos] = minetest.sound_play("xdecor_boiling_water", { pos = pos, max_hear_distance = 5, gain = 0.8, loop = true }) local meta = minetest.get_meta(pos) meta:set_string("infotext", S("Cauldron (active) - Drop foods inside to make a soup")) local timer = minetest.get_node_timer(pos) timer:start(5.0) end function cauldron.filling(pos, node, clicker, itemstack) local inv = clicker:get_inventory() local wield_item = clicker:get_wielded_item():get_name() if wield_item:sub(1,7) == "bucket:" then if wield_item:sub(-6) == "_empty" and not (node.name:sub(-6) == "_empty") then if itemstack:get_count() > 1 then if inv:room_for_item("main", "bucket:bucket_water 1") then itemstack:take_item() inv:add_item("main", "bucket:bucket_water 1") else minetest.chat_send_player(clicker:get_player_name(), S("No room in your inventory to add a bucket of water.")) return itemstack end else itemstack:replace("bucket:bucket_water") end minetest.set_node(pos, {name = "xdecor:cauldron_empty", param2 = node.param2}) elseif wield_item:sub(-6) == "_water" and node.name:sub(-6) == "_empty" then minetest.set_node(pos, {name = "xdecor:cauldron_idle", param2 = node.param2}) itemstack:replace("bucket:bucket_empty") end return itemstack end end function cauldron.idle_timer(pos) local below_node = {x = pos.x, y = pos.y - 1, z = pos.z} if not minetest.get_node(below_node).name:find("fire") then return true end local node = minetest.get_node(pos) minetest.set_node(pos, {name = "xdecor:cauldron_boiling", param2 = node.param2}) return true end -- Ugly hack to determine if an item has the function `minetest.item_eat` in its definition. local function eatable(itemstring) local item = itemstring:match("[%w_:]+") local on_use_def = minetest.registered_items[item].on_use if not on_use_def then return end return string.format("%q", string.dump(on_use_def)):find("item_eat") end function cauldron.boiling_timer(pos) local node = minetest.get_node(pos) local objs = minetest.get_objects_inside_radius(pos, 0.5) if not next(objs) then return true end local ingredients = {} for _, obj in pairs(objs) do if obj and not obj:is_player() and obj:get_luaentity().itemstring then local itemstring = obj:get_luaentity().itemstring local food = itemstring:match(":([%w_]+)") for _, ingredient in ipairs(ingredients_list) do if food and (eatable(itemstring) or food:find(ingredient)) then ingredients[#ingredients + 1] = food break end end end end if #ingredients >= 2 then for _, obj in pairs(objs) do obj:remove() end minetest.set_node(pos, {name = "xdecor:cauldron_soup", param2 = node.param2}) end local node_under = {x = pos.x, y = pos.y - 1, z = pos.z} if not minetest.get_node(node_under).name:find("fire") then minetest.set_node(pos, {name = "xdecor:cauldron_idle", param2 = node.param2}) end return true end function cauldron.take_soup(pos, node, clicker, itemstack) local inv = clicker:get_inventory() local wield_item = clicker:get_wielded_item() local item_name = wield_item:get_name() if item_name == "xdecor:bowl" or item_name == "farming:bowl" then if wield_item:get_count() > 1 then if inv:room_for_item("main", "xdecor:bowl_soup 1") then itemstack:take_item() inv:add_item("main", "xdecor:bowl_soup 1") else minetest.chat_send_player(clicker:get_player_name(), S("No room in your inventory to add a bowl of soup.")) return itemstack end else itemstack:replace("xdecor:bowl_soup 1") end minetest.set_node(pos, {name = "xdecor:cauldron_empty", param2 = node.param2}) end return itemstack end xdecor.register("cauldron_empty", { description = S("Cauldron"), groups = {cracky=2, oddly_breakable_by_hand=1}, on_rotate = screwdriver.rotate_simple, tiles = {"xdecor_cauldron_top_empty.png", "xdecor_cauldron_sides.png"}, infotext = S("Cauldron (empty)"), collision_box = xdecor.pixelbox(16, cauldron.cbox), on_rightclick = cauldron.filling, on_construct = function(pos) cauldron.stop_sound(pos) end, }) xdecor.register("cauldron_idle", { description = S("Cauldron (idle)"), groups = {cracky=2, oddly_breakable_by_hand=1, not_in_creative_inventory=1}, on_rotate = screwdriver.rotate_simple, tiles = {"xdecor_cauldron_top_idle.png", "xdecor_cauldron_sides.png"}, drop = "xdecor:cauldron_empty", infotext = S("Cauldron (idle)"), collision_box = xdecor.pixelbox(16, cauldron.cbox), on_rightclick = cauldron.filling, on_construct = cauldron.idle_construct, on_timer = cauldron.idle_timer, }) xdecor.register("cauldron_boiling", { description = S("Cauldron (active)"), groups = {cracky=2, oddly_breakable_by_hand=1, not_in_creative_inventory=1}, on_rotate = screwdriver.rotate_simple, drop = "xdecor:cauldron_empty", infotext = S("Cauldron (active) - Drop foods inside to make a soup"), damage_per_second = 2, tiles = { { name = "xdecor_cauldron_top_anim_boiling_water.png", animation = {type = "vertical_frames", length = 3.0} }, "xdecor_cauldron_sides.png" }, collision_box = xdecor.pixelbox(16, cauldron.cbox), on_rightclick = cauldron.filling, on_construct = cauldron.boiling_construct, on_timer = cauldron.boiling_timer, on_destruct = function(pos) cauldron.stop_sound(pos) end, }) xdecor.register("cauldron_soup", { description = S("Cauldron (active)"), groups = {cracky = 2, oddly_breakable_by_hand = 1, not_in_creative_inventory = 1}, on_rotate = screwdriver.rotate_simple, drop = "xdecor:cauldron_empty", infotext = S("Cauldron (active) - Use a bowl to eat the soup"), damage_per_second = 2, tiles = { { name = "xdecor_cauldron_top_anim_soup.png", animation = {type = "vertical_frames", length = 3.0} }, "xdecor_cauldron_sides.png" }, collision_box = xdecor.pixelbox(16, cauldron.cbox), on_rightclick = cauldron.take_soup, on_destruct = function(pos) cauldron.stop_sound(pos) end, }) -- Craft items minetest.register_craftitem("xdecor:bowl", { description = S("Bowl"), inventory_image = "xdecor_bowl.png", wield_image = "xdecor_bowl.png", groups = {food_bowl = 1, flammable = 2}, }) minetest.register_craftitem("xdecor:bowl_soup", { description = S("Bowl of soup"), inventory_image = "xdecor_bowl_soup.png", wield_image = "xdecor_bowl_soup.png", groups = {not_in_creative_inventory=1}, stack_max = 1, on_use = minetest.item_eat(30, "xdecor:bowl") }) -- Recipes minetest.register_craft({ output = "xdecor:bowl 3", recipe = { {"group:wood", "", "group:wood"}, {"", "group:wood", ""} } }) minetest.register_craft({ output = "xdecor:cauldron_empty", recipe = { {"default:iron_lump", "", "default:iron_lump"}, {"default:iron_lump", "", "default:iron_lump"}, {"default:iron_lump", "default:iron_lump", "default:iron_lump"} } })
-------------------------------------------------------------------------------- -- Handler.......... : onInit -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function curl_test.onInit ( ) -------------------------------------------------------------------------------- application.setOption ( application.kOptionSwapInterval, 1 ) user.postEvent ( this.getUser ( ), 3, "curl_test", "onLaunchThreads" ) -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
local ffi = require("ffi") local bits_ioctl = require("bits/ioctl") ffi.cdef[[ int ioctl (int, int, ...); ]] local exports = { ioctl = ffi.C.ioctl; } setmetatable(exports, { __call = function(self, tbl) tbl = tbl or _G; for k,v in pairs(self) do tbl[k] = v; end return self; end, }) return exports
-- x64 ioctl differences return function(s) local arch = { ioctl = { } } return arch end
if SERVER then AddCSLuaFile() util.AddNetworkString("ThirdOTSPacket") util.AddNetworkString("ThirdOTSReq") net.Receive("ThirdOTSReq", function(len, ply) local t = net.ReadBool() local state = net.ReadBool() if t then ply:SetNW2Bool("ThirtOTS", state) else ply:SetNW2Bool("ThirtOTS_SStatus", state) end end) hook.Add("PlayerSay", "tfaweaponssuck", function(ply, text, public) local text = string.lower(text) if (text == "tfa weapons are broken" or text == "tfa weapons suck" or text == "weapon is broken" ) then ply:ConCommand("tfa_rp_friendly_notify") end end) hook.Add("PlayerSay", "thirdperson_ots", function(ply, text, public) local text = string.lower(text) -- Make the chat message entirely lowercase if (text == "!thirdperson" or text == "!3p" or text == "!thirdperson_ots" or text == "!3rdperson" or text == "!ots_thirdperson" or text == "!tp_ots") then ply:ConCommand("thirdperson_ots") return "" end end) hook.Add("PlayerSay", "tfa_rp_friendly_menu ", function(ply, text, public) local text = string.lower(text) -- Make the chat message entirely lowercase if (text == "!tfahelp" ) then ply:ConCommand("tfa_rp_friendly_menu ") return "" end end) hook.Add("PlayerSay", "thirdperson_ots_reset", function(ply, text, public) local text = string.lower(text) -- Make the chat message entirely lowercase if (text == "!thirdperson_reset" or text == "!3p_reset" or text == "!thirdperson_ots_reset" or text == "!3rdperson_reset" or text == "!ots_thirdperson_reset" or text == "!tp_ots_reset") then ply:ConCommand("thirdperson_ots") return "" end end) hook.Add("PlayerSay", "thirdperson_ots_swap", function(ply, text, public) local text = string.lower(text) -- Make the chat message entirely lowercase if (text == "!thirdperson_swap" or text == "!3p_swap" or text == "!thirdperson_ots_swap" or text == "!3rdperson_swap" or text == "!ots_thirdperson_swap") then ply:ConCommand("thirdperson_ots_swap") return "" end end) end concommand.Add("thirdperson_ots", function(fply, cmd, args, argstr) if CLIENT then net.Start("ThirdOTSReq") net.WriteBool(true) net.WriteBool(not fply:GetNW2Bool("ThirtOTS", false)) net.SendToServer() end fply:SetNW2Bool("ThirtOTS", not fply:GetNW2Bool("ThirtOTS", false)) end, nil, nil, FCVAR_NONE) concommand.Add("thirdperson_ots_swap", function(fply, cmd, args, argstr) if CLIENT then net.Start("ThirdOTSReq") net.WriteBool(false) net.WriteBool(not fply:GetNW2Bool("ThirtOTS_SStatus", false)) net.SendToServer() end fply:SetNW2Bool("ThirtOTS_SStatus", not fply:GetNW2Bool("ThirtOTS_SStatus", false)) end, nil, nil, FCVAR_NONE) function PointDir(from, to) local ang = to - from return ang:Angle() end local minvec = Vector(-6, -6, -6) local maxvec = Vector(6, 6, 6) local crouchfac = 0 local rightconvar = CreateClientConVar("thirdperson_ots_right", 20, true, false) local upconvar = CreateClientConVar("thirdperson_ots_up", 0, true, false) local upcrouchedconvar = CreateClientConVar("thirdperson_ots_crouched_up", 15, true, false) local forwardconvar = CreateClientConVar("thirdperson_ots_forward", -35, true, false) local crosscv = CreateClientConVar("thirdperson_ots_crosshair", 1, true, false) local fovcv = CreateClientConVar("thirdperson_ots_fov", 100, true, false) local lply local function chkfunc(ent) if not lply and IsValid(LocalPlayer()) then lply = LocalPlayer() end if ent == lply or (IsValid(ply) and ent == ply:GetActiveWeapon()) then return false end if ent:IsRagdoll() then return false end return true end local angleclamp = 85 local oldeyeangles local neweyeangles local tr = {} local traceres local swapfac = 1 local swaptarget = 1 hook.Add("CalcView", "ThirdOTSCalcView", function(fply, pos, angles, fov) if not fply:GetNW2Bool("ThirtOTS", false) then return end if not fply:Alive() then return end swaptarget = fply:GetNW2Bool("ThirtOTS_SStatus", false) and -1 or 1 swapfac = math.Approach(swapfac, swaptarget, (swaptarget - swapfac) * FrameTime() * 10) oldeyeangles = fply:EyeAngles() --angles * 1 if not fply.thirdotscameraangle then angles.p = math.Clamp(angles.p, -angleclamp, angleclamp) fply.thirdotscameraangle = angles end angles = fply.thirdotscameraangle if fply.oldeyeangles then local dif = fply:EyeAngles() - fply.oldeyeangles fply.thirdotscameraangle = fply.thirdotscameraangle + dif end fply.thirdotscameraangle:Normalize() fply.thirdotscameraangle.p = math.Clamp(fply.thirdotscameraangle.p, -angleclamp, angleclamp) angles:Normalize() local tmpang = Angle(angles.p, angles.y, angles.r) tr.start = pos tr.endpos = pos + (tmpang:Forward() * forwardconvar:GetFloat()) + (tmpang:Right() * rightconvar:GetFloat() * swapfac) + (tmpang:Up() * upconvar:GetFloat()) local newnum = fply:Crouching() and 1 or 0 crouchfac = math.Approach(crouchfac, newnum, (newnum - crouchfac) * FrameTime() * 10) if crouchfac > 0 then tr.endpos = tr.endpos + (tmpang:Up() * upcrouchedconvar:GetFloat()) * crouchfac end tr.filter = chkfunc tr.mask = MASK_SOLID tr.mins = minvec tr.maxs = maxvec local htra = util.TraceHull(tr) local tmppos = htra.HitPos tr.start = tmppos - tmpang:Forward() * forwardconvar:GetFloat() * 2 tr.endpos = tmpang:Forward() * 2147483647 tr.mask = MASK_SHOT tr.filter = chkfunc --tmppos,tmpang:Forward()*2147483647,filtertable traceres = util.TraceLine(tr) neweyeangles = PointDir(fply:GetShootPos(), traceres.HitPos) neweyeangles:Normalize() local vpan = fply:GetViewPunchAngles() vpan:Normalize() fply:SetEyeAngles(LerpAngle(FrameTime() * 10, oldeyeangles, neweyeangles)) fply.oldeyeangles = fply:EyeAngles() fply.campos = tmppos fply.camang = tmpang tmpang = tmpang + vpan * 1 tmpang.r = 0 if fovcv then fov = fov * math.Clamp( fovcv:GetFloat(), 50, 150) / 90 end if LeanCalcView then return LeanCalcView(fply, tmppos, tmpang, fov) else return { origin = tmppos, angles = tmpang, fov = fov } end end) hook.Add("ShouldDrawLocalPlayer", "ThirdOTSShouldDrawLocalPlayer", function(fply) if not fply:GetNW2Bool("ThirtOTS", false) then return end return true end) hook.Add("HUDPaint", "ThirdOTSHudPaint", function() local fply = LocalPlayer() if not IsValid(fply) then return end if not fply:GetNW2Bool("ThirtOTS", false) then return end if not fply.interpposx then fply.interpposx = ScrW() / 2 end if not fply.interpposy then fply.interpposy = ScrH() / 2 end local pos = (fply:GetEyeTrace().HitPos):ToScreen() pos.x = math.Clamp(pos.x, 0, ScrW()) pos.y = math.Clamp(pos.y, 0, ScrH()) fply.interpposx = math.Approach(fply.interpposx, pos.x, (fply.interpposx - pos.x) * FrameTime() * 25) fply.interpposy = math.Approach(fply.interpposy, pos.y, (fply.interpposy - pos.y) * FrameTime() * 25) draw.NoTexture() local s_cone s_cone = 0.015 local wep = fply:GetActiveWeapon() if IsValid(wep) and wep.CalculateConeRecoil then s_cone = wep:CalculateConeRecoil() end local gap = (s_cone * 90) / fply:GetFOV() * ScrH() / 1.44 --surface.DrawCircle( fply.interpposx, fply.interpposy, math.Clamp(gap,6,ScrH()/2), col ) --if Vector(fply.interpposx, fply.interpposy, 0):Distance(Vector(ScrW() / 2, ScrH() / 2, 0)) < ScrH() / 60 then -- surface.DrawCircle(ScrW() / 2, ScrH() / 2, math.Clamp(gap, 6, ScrH() / 2), greencol) --else -- surface.DrawCircle(ScrW() / 2, ScrH() / 2, math.Clamp(gap, 6, ScrH() / 2), redcol) --end if ( not crosscv ) or crosscv:GetBool() then surface.DrawCircle(ScrW() / 2, ScrH() / 2, math.Clamp(gap, 6, ScrH() / 2), color_white) end end) local DisabledMoveTypes = { [MOVETYPE_FLY] = true, [MOVETYPE_FLYGRAVITY] = true, [MOVETYPE_OBSERVER] = true, [MOVETYPE_NOCLIP] = true } hook.Add("CreateMove", "ThirdOTSCreateMove", function(cmd) local fply = LocalPlayer() if not IsValid(fply) then return end if not fply:GetNW2Bool("ThirtOTS", false) then return end if DisabledMoveTypes[fply:GetMoveType()] then return end local tang = fply.camang and fply.camang or fply:EyeAngles() vel = Vector(cmd:GetForwardMove(), cmd:GetSideMove(), cmd:GetUpMove()) vel:Rotate(fply:EyeAngles() - tang) cmd:SetSideMove(vel.y) cmd:SetForwardMove(vel.x) cmd:SetUpMove(vel.z) end)
local re = require 're' local make_context = require 'parse.json.make.context' local make_read_value = require 'parse.json.make.read.value' local pdef_document = [[ %SPACE %VALUE !. ]] return function(context) context = context or make_context() context.VALUE = make_read_value(context) return re.compile(pdef_document, context) end
Frame = class() function Frame:init(left, bottom, right, top) -- you can accept and set parameters here self.left = left self.right = right self.bottom = bottom self.top = top end function Frame:overlaps(f) if self.left > f.right or self.right < f.left or self.bottom > f.top or self.top < f.bottom then return false else return true end end
return { { "button", { background_color = { 78, 189, 255, 255 }, border_radius = 4, text_color = { 19, 86, 128, 255 }, text_align = "center", line_height = 2, padding = { 0, 15 }, cursor = "hand", text_shadow = { 0, 1 }, text_shadow_color = { 200, 200, 200, 100 }, }}, { "button:hover", { background_color = { 122, 206, 253, 255 }, }}, { "button:lclick", { background_color = { 33, 174, 254, 255 }, }}, { "button:focus", { background_color = { 189, 78, 255, 255 }, }}, }
--从高到低 --^ --not - (unary) --* / --+ - --.. --< > <= >= ~= == --and --or --除了^和..所有的运算符左连接 -- --[[ a+i < b/2+1 <--> (a+i) < ((b/2)+1) 5+x^2*8 <--> 5+((x^2)*8) a < y and y <= z <--> (a < y) and (y <= z) -x^2 <--> -(x^2) x^y^z <--> x^(y^z) --]]
--[[ Play caller ID/envelope information. ]] -- Coming from where? Could be either prior to playing the message, or from -- the advanced menu options. from = args(1) -- Always play both if we're coming from the advanced options. if from == "advanced_options" then play_envelope = "yes" play_caller_id = "yes" -- Otherwise, only play the information according to the mailbox settings. else play_envelope = storage("mailbox_settings", "play_envelope") play_caller_id = storage("mailbox_settings", "play_caller_id") end -- Message data. message_number = storage("counter", "message_number") timestamp = storage("message", "timestamp_" .. message_number) caller_id_number = storage("message", "caller_id_number_" .. message_number) return { { action = "play_phrase", phrase = "cid_envelope", phrase_arguments = play_envelope .. ":" .. timestamp .. ":" .. play_caller_id .. ":" .. caller_id_number, keys = { ["1"] = "top:play_message", ["2"] = "top:change_folders", ["3"] = "top:advanced_options", ["4"] = "top:prev_message", ["5"] = "top:repeat_message", ["6"] = "top:next_message", ["7"] = "top:delete_undelete_message", ["8"] = "top:forward_message_menu", ["9"] = "top:save_message", ["*"] = "help", ["#"] = "exit", }, }, { action = "conditional", value = from, compare_to = "advanced_options", comparison = "equal", if_true = "top:message_options", }, }
build_path = os.getenv("BUILDDIR") package.cpath = build_path..'/test/box/?.so;'..build_path..'/test/box/?.dylib;'..package.cpath log = require('log') net = require('net.box') c = net.connect(os.getenv("LISTEN")) box.schema.func.create('function1', {language = "C"}) id = box.func["function1"].id function setmap(tab) return setmetatable(tab, { __serialize = 'map' }) end datetime = os.date("%Y-%m-%d %H:%M:%S") box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'procedure', {}, 'any', 'none', 'none', false, false, true, {"LUA"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'any', 'none', 'reads', false, false, true, {"LUA"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'any', 'none', 'none', false, false, false, {"LUA"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'data', 'none', 'none', false, false, true, {"LUA"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'any', 'none', 'none', false, false, true, {"LUA", "C"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'any', 'aggregate', 'none', false, false, true, {"LUA"}, setmap({}), '', datetime, datetime} box.space._func:replace{id, 1, 'function1', 0, 'LUA', '', 'function', {}, 'any', 'none', 'none', false, false, true, {"LUA"}, setmap({}), '', datetime, datetime} box.schema.user.grant('guest', 'execute', 'function', 'function1') _ = box.schema.space.create('test') _ = box.space.test:create_index('primary') box.schema.user.grant('guest', 'read,write', 'space', 'test') c:call('function1') box.schema.func.drop("function1") box.schema.func.create('function1.args', {language = "C"}) box.schema.user.grant('guest', 'execute', 'function', 'function1.args') c:call('function1.args') c:call('function1.args', { "xx" }) c:call('function1.args', { 15 }) box.func["function1.args"] box.func["function1.args"]:call() box.func["function1.args"]:call({ "xx" }) box.func["function1.args"]:call({ 15 }) box.schema.func.drop("function1.args") box.func["function1.args"] box.schema.func.create('function1.multi_inc', {language = "C"}) box.schema.user.grant('guest', 'execute', 'function', 'function1.multi_inc') c:call('function1.multi_inc') box.space.test:select{} c:call('function1.multi_inc', { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) box.space.test:select{} c:call('function1.multi_inc', { 2, 4, 6, 8, 10 }) box.space.test:select{} c:call('function1.multi_inc', { 0, 2, 4 }) box.space.test:select{} box.schema.func.drop("function1.multi_inc") box.schema.func.create('function1.errors', {language = "C"}) box.schema.user.grant('guest', 'execute', 'function', 'function1.errors') c:call('function1.errors') box.schema.func.drop("function1.errors") box.schema.func.create('xxx', {language = 'invalid'}) -- language normalization function func_lang(name) return (box.space._func.index[2]:select{name}[1] or {})[5] end box.schema.func.create('f11'), func_lang('f11') box.schema.func.create('f12', {language = 'Lua'}), func_lang('f12') box.schema.func.create('f13', {language = 'lua'}), func_lang('f13') box.schema.func.create('f14', {language = 'lUa'}), func_lang('f14') box.schema.func.create('f15', {language = 'c'}), func_lang('f15') box.schema.func.create('f16', {language = 'C'}), func_lang('f16') box.schema.func.drop("f11") box.schema.func.drop("f12") box.schema.func.drop("f13") box.schema.func.drop("f14") box.schema.func.drop("f15") box.schema.func.drop("f16") box.space.test:drop() -- Missing shared library name = 'unkownmod.unknownfunc' box.schema.func.create(name, {language = 'C'}) box.schema.user.grant('guest', 'execute', 'function', name) c:call(name) box.schema.func.drop(name) -- Drop function while executing gh-910 box.schema.func.create('function1.test_yield', {language = "C"}) box.schema.user.grant('guest', 'execute', 'function', 'function1.test_yield') s = box.schema.space.create('test_yield') _ = s:create_index('pk') box.schema.user.grant('guest', 'read,write', 'space', 'test_yield') fiber = require('fiber') ch = fiber.channel(1) _ = fiber.create(function() c:call('function1.test_yield') ch:put(true) end) while s:get({1}) == nil do fiber.yield(0.0001) end box.schema.func.drop('function1.test_yield') ch:get() s:drop() -- gh-2914: check identifier constraints. test_run = require('test_run').new() test_run:cmd("push filter '(.builtin/.*.lua):[0-9]+' to '\\1'") identifier = require("identifier") test_run:cmd("setopt delimiter ';'") -- -- '.' in func name is used to point out path therefore '.' in name -- itself is prohibited -- -- identifier.run_test( function (identifier) if identifier == "." then return end box.schema.func.create(identifier, {language = "lua"}) box.schema.user.grant('guest', 'execute', 'function', identifier) rawset(_G, identifier, function () return 1 end) local res = pcall(c.call, c, identifier) if c:call(identifier) ~= 1 then error("Should not fire") end rawset(_G, identifier, nil) end, function (identifier) if identifier == "." then return end box.schema.func.drop(identifier) end ); test_run:cmd("setopt delimiter ''"); c:close() -- -- gh-2233: Invoke Lua functions created outside SQL. -- box.schema.func.create('WAITFOR', {language = 'SQL_BUILTIN', \ param_list = {'integer'}, returns = 'integer',exports = {'SQL'}}) test_run:cmd("setopt delimiter ';'") box.schema.func.create("function1.divide", {language = 'C', returns = 'number', is_deterministic = true, exports = {'LUA'}}) test_run:cmd("setopt delimiter ''"); box.execute('SELECT "function1.divide"()') box.func["function1.divide"]:drop() test_run:cmd("setopt delimiter ';'") box.schema.func.create("function1.divide", {language = 'C', returns = 'number', is_deterministic = true, exports = {'LUA', 'SQL'}}) test_run:cmd("setopt delimiter ''"); box.execute('SELECT "function1.divide"()') box.execute('SELECT "function1.divide"(6)') box.execute('SELECT "function1.divide"(6, 3)') box.func["function1.divide"]:drop() test_run:cmd("setopt delimiter ';'") box.schema.func.create("function1.divide", {language = 'C', returns = 'number', param_list = {'number', 'number'}, is_deterministic = true, exports = {'LUA', 'SQL'}}) test_run:cmd("setopt delimiter ''"); box.execute('SELECT "function1.divide"()') box.execute('SELECT "function1.divide"(6)') box.execute('SELECT "function1.divide"(6, 3, 3)') box.execute('SELECT "function1.divide"(6, 3)') box.execute('SELECT "function1.divide"(5, 2)') box.func["function1.divide"]:drop() function SUMMARIZE(a, b) return a + b end test_run:cmd("setopt delimiter ';'") box.schema.func.create("SUMMARIZE", {language = 'LUA', returns = 'number', is_deterministic = true, param_list = {'number', 'number'}, exports = {'LUA', 'SQL'}}) test_run:cmd("setopt delimiter ''"); box.execute('SELECT summarize(1, 2)') box.func.SUMMARIZE:drop() test_run:cmd("setopt delimiter ';'") box.schema.func.create("SUMMARIZE", {language = 'LUA', returns = 'number', body = 'function (a, b) return a + b end', is_deterministic = true, param_list = {'number', 'number'}, exports = {'LUA', 'SQL'}}) test_run:cmd("setopt delimiter ''"); box.execute('SELECT summarize(1, 2)') box.func.SUMMARIZE:drop() -- -- gh-4113: Valid method to use Lua from SQL -- box.execute('SELECT lua(\'return 1 + 1\')') box.execute('SELECT lua(\'return box.cfg\')') box.execute('SELECT lua(\'return box.cfg()\')') box.execute('SELECT lua(\'return box.cfg.memtx_memory\')') -- Test registered functions interface. function divide(a, b) return a / b end box.schema.func.create("divide", {comment = 'Divide two values'}) func = box.func.divide func.call({4, 2}) func:call(4, 2) func:call() func:call({}) func:call({4}) func:call({4, 2}) func:call({4, 2, 1}) func:drop() func func.drop() box.func.divide func:drop() func:call({4, 2}) box.internal.func_call('divide', 4, 2) box.schema.func.create("function1.divide", {language = 'C'}) func = box.func["function1.divide"] func:call(4, 2) func:call() func:call({}) func:call({4}) func:call({4, 2}) func:call({4, 2, 1}) func:drop() box.func["function1.divide"] func func:drop() func:call({4, 2}) box.internal.func_call('function1.divide', 4, 2) test_run:cmd("setopt delimiter ';'") function minmax(array) local min = 999 local max = -1 for _, v in pairs(array) do min = math.min(min, v) max = math.max(max, v) end return min, max end test_run:cmd("setopt delimiter ''"); box.schema.func.create("minmax") func = box.func.minmax func:call({{1, 2, 99, 3, -1}}) func:drop() box.func.minmax -- Test access checks for registered functions. function secret() return 1 end box.schema.func.create("secret") box.func.secret:call({}) function secret_leak() return box.func.secret:call() end box.schema.func.create('secret_leak') box.schema.user.grant('guest', 'execute', 'function', 'secret_leak') conn = net.connect(box.cfg.listen) conn:call('secret_leak') conn:close() box.schema.user.revoke('guest', 'execute', 'function', 'secret_leak') box.schema.func.drop('secret_leak') box.schema.func.drop('secret') -- -- gh-4182: Introduce persistent Lua functions. -- test_run:cmd("setopt delimiter ';'") body = [[function(tuple) if type(tuple.address) ~= 'string' then return nil, 'Invalid field type' end local t = tuple.address:upper():split() for k,v in pairs(t) do t[k] = v end return t end ]] test_run:cmd("setopt delimiter ''"); box.schema.func.create('addrsplit', {body = body, language = "C"}) box.schema.func.create('addrsplit', {is_sandboxed = true, language = "C"}) box.schema.func.create('addrsplit', {is_sandboxed = true}) box.schema.func.create('invalid', {body = "function(tuple) ret tuple"}) box.schema.func.create('addrsplit', {body = body, is_deterministic = true}) box.schema.user.grant('guest', 'execute', 'function', 'addrsplit') conn = net.connect(box.cfg.listen) conn:call('addrsplit', {{address = "Moscow Dolgoprudny"}}) box.func.addrsplit:call({{address = "Moscow Dolgoprudny"}}) conn:close() box.snapshot() test_run:cmd("restart server default") test_run = require('test_run').new() test_run:cmd("push filter '(.builtin/.*.lua):[0-9]+' to '\\1'") net = require('net.box') conn = net.connect(box.cfg.listen) conn:call('addrsplit', {{address = "Moscow Dolgoprudny"}}) box.func.addrsplit:call({{address = "Moscow Dolgoprudny"}}) conn:close() box.schema.user.revoke('guest', 'execute', 'function', 'addrsplit') box.func.addrsplit:drop() -- Test sandboxed functions. test_run:cmd("setopt delimiter ';'") body = [[function(number) math.abs = math.log return math.abs(number) end]] test_run:cmd("setopt delimiter ''"); box.schema.func.create('monkey', {body = body, is_sandboxed = true}) box.func.monkey:call({1}) math.abs(1) box.func.monkey:drop() sum = 0 function inc_g(val) sum = sum + val end box.schema.func.create('call_inc_g', {body = "function(val) inc_g(val) end"}) box.func.call_inc_g:call({1}) assert(sum == 1) box.schema.func.create('call_inc_g_safe', {body = "function(val) inc_g(val) end", is_sandboxed = true}) box.func.call_inc_g_safe:call({1}) assert(sum == 1) box.func.call_inc_g:drop() box.func.call_inc_g_safe:drop() -- Test persistent function assemble corner cases box.schema.func.create('compiletime_tablef', {body = "{}"}) box.schema.func.create('compiletime_call_inc_g', {body = "inc_g()"}) assert(sum == 1) test_run:cmd("clear filter") -- -- Check that function cache is updated synchronously with _func changes. -- box.begin() box.schema.func.create('test') f = box.func.test box.rollback() f ~= nil box.func.test == nil box.schema.func.create('test') f = box.func.test box.begin() box.space._func:delete{f.id} f = box.func.test box.rollback() f == nil box.func.test ~= nil box.func.test:drop() -- Check SQL builtins test_run:cmd("setopt delimiter ';'") sql_builtin_list = { "TRIM", "TYPEOF", "PRINTF", "UNICODE", "CHAR", "HEX", "VERSION", "QUOTE", "REPLACE", "SUBSTR", "GROUP_CONCAT", "JULIANDAY", "DATE", "TIME", "DATETIME", "STRFTIME", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_DATE", "LENGTH", "POSITION", "ROUND", "UPPER", "LOWER", "IFNULL", "RANDOM", "CEIL", "CEILING", "CHARACTER_LENGTH", "CHAR_LENGTH", "FLOOR", "MOD", "OCTET_LENGTH", "ROW_COUNT", "COUNT", "LIKE", "ABS", "EXP", "LN", "POWER", "SQRT", "SUM", "TOTAL", "AVG", "RANDOMBLOB", "NULLIF", "ZEROBLOB", "MIN", "MAX", "COALESCE", "EVERY", "EXISTS", "EXTRACT", "SOME", "GREATER", "LESSER", "SOUNDEX", "LIKELIHOOD", "LIKELY", "UNLIKELY", "_sql_stat_get", "_sql_stat_push", "_sql_stat_init", "GREATEST", "LEAST" } test_run:cmd("setopt delimiter ''"); ok = true for _, v in pairs(sql_builtin_list) do ok = ok and (box.space._func.index.name:get(v) ~= nil) end ok == true box.func.LUA:call({"return 1 + 1"}) box.schema.user.grant('guest', 'execute', 'function', 'SUM') c = net.connect(box.cfg.listen) c:call("SUM") c:close() box.schema.user.revoke('guest', 'execute', 'function', 'SUM') box.schema.func.drop("SUM") -- Introduce function options box.schema.func.create('test', {body = "function(tuple) return tuple end", is_deterministic = true, opts = {is_multikey = true}}) box.func['test'].is_multikey == true box.func['test']:drop()
local B = require("core.Broadcast") local Logger = require("core.Logger") local Combat = loadfile("bundles/bundle-example-combat/lib/Combat.lua")() local wrapper = require("core.lib.wrapper") return { aliases = { "attack", "slay" }, command = function(state) ---comment ---@param self any ---@param args any ---@param player Character ---@return any return function(self, args, player) args = wrapper.trim(args) if #args < 1 then return B.sayAt(player, "Kill whom?") end local ok, target = pcall(Combat.findCombatant, player, args) if not ok then Logger.error(tostring(res)) return B.sayAt(player, res) end if not target then return B.sayAt(player, "They are not here.") end B.sayAt(player, string.format("You attack %q", target.name)) player:initiateCombat(target) B.sayAtExcept(player.room, string.format("%q attacks %q", player.name, target.name), { player, target }) if not target:isNpc() then B.sayAt(target, string.format("%q attacks you!", player.name)) end end end, }
return {'paquay'}
t = {"a", "b", "c"} index, el = next(t) print(index) print(el) index, el = next(t, index) print(index) print(el) index, el = next(t, index) print(index) print(el) index, el = next(t, index) print(index) print(el)
require("core/object"); require("gameData/gameData"); require("libs/json_wrap"); -------------------------------- --用户等级配置 ----------------------------------- local UserLevelConfig = class(GameData); UserLevelConfig.initData = function(self) self.m_localVersion = -1; self.m_level = {}; end UserLevelConfig.loadDictData = function(self, dict) self.m_localVersion = dict:getInt("version", -1); local strData = dict:getString("levelData") or ""; local levelData = json.decode(strData); if table.isTable(levelData) then self:analysisData(levelData); end end UserLevelConfig.saveDictData = function(self, dict) dict:setInt("version", self:getLocalVersion() ); local strLevelData = json.encode(self.m_level or {} ); if strLevelData then dict:setString("levelData", strLevelData); end end UserLevelConfig.getLocalDictName = function(self) return "userLevelConfig"; end UserLevelConfig.getLocalVersion = function(self) return self.m_localVersion or -1; end UserLevelConfig.requestData = function(self) if not self.m_isTouched or table.isEmpty(self.m_level) then local param = { ["cli_ver"] = self:getLocalVersion(); }; OnlineSocketManager.getInstance():sendMsg(PHP_LEVEL_MEDEL_CONFIG,param); end end UserLevelConfig.onLevelConfigCallBack = function(self,isSuccess,info) Log.v("UserLevelConfig.onLevelConfigCallBack","isSuccess = ",isSuccess,"info = ",info); if isSuccess then self:updateDataByCompareVersion(info.svr_ver, info.isrefresh, info.level); end end UserLevelConfig.updateMemData = function(self, serverVersion, levelData) if table.isEmpty(levelData) then return; end self.m_localVersion = serverVersion; self:analysisData(levelData); end UserLevelConfig.analysisData = function(self, levelData) if type(levelData) ~= "table" then return; end self.m_level = {}; for k,v in pairs(levelData) do v.exp = tonumber(v.exp) or 0; v.name = tostring(v.name) or ""; v.levelId = tonumber(k) or 0; self.m_level[number.valueOf(k)] = v; end table.sort(self.m_level, function(a, b) return a.levelId < b.levelId; end ); end UserLevelConfig.s_socketCmdFuncMap = { [PHP_LEVEL_MEDEL_CONFIG] = UserLevelConfig.onLevelConfigCallBack; }; ---------------------------------------------------- UserLevelConfig.getUserLevelConfig = function(self) self:requestData(); local config = self.m_level; if table.isEmpty(config) then config = self:_getDefaultLevelConfig(); end return config; end UserLevelConfig._getDefaultLevelConfig = function(self) return UserLevelConfig.defaultLevelConfig ; end UserLevelConfig.defaultLevelConfig = { [0]= { ["name"]= "初出茅庐", ["exp"]= 0, }, [1]= { ["name"]= "入世未深", ["exp"]= 1, }, [2]= { ["name"]= "入世未深", ["exp"]= 4, }, [3]= { ["name"]= "入世未深", ["exp"]= 8, }, [4]= { ["name"]= "入世未深", ["exp"]= 14, }, [5]= { ["name"]= "入世未深", ["exp"]= 21, }, [6]= { ["name"]= "闯荡江湖", ["exp"]= 30, }, [7]= { ["name"]= "闯荡江湖", ["exp"]= 40, }, [8]= { ["name"]= "闯荡江湖", ["exp"]= 53, }, [9]= { ["name"]= "闯荡江湖", ["exp"]= 69, }, [10]= { ["name"]= "闯荡江湖", ["exp"]= 87, }, [11]= { ["name"]= "小试身手", ["exp"]= 167, }, [12]= { ["name"]= "小试身手", ["exp"]= 292, }, [13]= { ["name"]= "小试身手", ["exp"]= 512, }, [14]= { ["name"]= "小试身手", ["exp"]= 927, }, [15]= { ["name"]= "小试身手", ["exp"]= 1732, }, [16]= { ["name"]= "初露头角", ["exp"]= 3322, }, [17]= { ["name"]= "初露头角", ["exp"]= 6482, }, [18]= { ["name"]= "初露头角", ["exp"]= 12787, }, [19]= { ["name"]= "初露头角", ["exp"]= 25387, }, [20]= { ["name"]= "初露头角", ["exp"]= 50582, }, [21]= { ["name"]= "略有小成", ["exp"]= 56917, }, [22]= { ["name"]= "略有小成", ["exp"]= 63282, }, [23]= { ["name"]= "略有小成", ["exp"]= 69737, }, [24]= { ["name"]= "略有小成", ["exp"]= 76462, }, [25]= { ["name"]= "略有小成", ["exp"]= 84002, }, [26]= { ["name"]= "一鸣惊人", ["exp"]= 93997, }, [27]= { ["name"]= "一鸣惊人", ["exp"]= 111367, }, [28]= { ["name"]= "一鸣惊人", ["exp"]= 150862, }, [29]= { ["name"]= "一鸣惊人", ["exp"]= 256732, }, [30]= { ["name"]= "一鸣惊人", ["exp"]= 561727, }, [31]= { ["name"]= "赫赫有名", ["exp"]= 579137, }, [32]= { ["name"]= "赫赫有名", ["exp"]= 596587, }, [33]= { ["name"]= "赫赫有名", ["exp"]= 614157, }, [34]= { ["name"]= "赫赫有名", ["exp"]= 632087, }, [35]= { ["name"]= "赫赫有名", ["exp"]= 651107, }, [36]= { ["name"]= "威震四方", ["exp"]= 673407, }, [37]= { ["name"]= "威震四方", ["exp"]= 705547, }, [38]= { ["name"]= "威震四方", ["exp"]= 767207, }, [39]= { ["name"]= "威震四方", ["exp"]= 917437, }, [40]= { ["name"]= "威震四方", ["exp"]= 1333387, }, [41]= { ["name"]= "天下无敌", ["exp"]= 1365557, }, [42]= { ["name"]= "天下无敌", ["exp"]= 1397757, }, [43]= { ["name"]= "天下无敌", ["exp"]= 1430052, }, [44]= { ["name"]= "天下无敌", ["exp"]= 1462662, }, [45]= { ["name"]= "天下无敌", ["exp"]= 1496287, }, [46]= { ["name"]= "至尊霸主", ["exp"]= 1533162, }, [47]= { ["name"]= "至尊霸主", ["exp"]= 1580437, }, [48]= { ["name"]= "至尊霸主", ["exp"]= 1660997, }, [49]= { ["name"]= "至尊霸主", ["exp"]= 1848072, }, [50]= { ["name"]= "至尊霸主", ["exp"]= 2375992, } } return UserLevelConfig;
local status_ok, key = pcall(require, "which-key") if not status_ok then return end key.setup { plugins = { marks = true, -- shows a list of your marks on ' and ` registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode -- the presets plugin, adds help for a bunch of default keybindings in Neovim -- No actual key bindings are created presets = { operators = false, -- adds help for operators like d, y, ... motions = false, -- adds help for motions text_objects = false, -- help for text objects triggered after entering an operator windows = true, -- default bindings on <c-w> nav = true, -- misc bindings to work with windows z = true, -- bindings for folds, spelling and others prefixed with z g = true -- bindings for prefixed with g } }, icons = { breadcrumb = "»", -- symbol used in the command line area that shows your active key combo separator = "➜", -- symbol used between a key and it's label group = "" -- symbol prepended to a group }, window = { border = require"general.misc".border, -- none, single, double, shadow position = "bottom", -- bottom, top margin = {1, 0, 1, 0}, -- extra window margin [top, right, bottom, left] padding = {2, 2, 2, 2} -- extra window padding [top, right, bottom, left] }, layout = { height = {min = 4, max = 25}, -- min and max height of the columns width = {min = 20, max = 50}, -- min and max width of the columns spacing = 3 -- spacing between columns }, hidden = {"<silent>", "<cmd>", "<Cmd>", "<CR>", "call", "lua", "^:", "^ "}, -- hide mapping boilerplate show_help = false -- show help message on the command line when the popup is visible } --> OPTIONS APPLIED TO EACH MAPPING local opts = { mode = "n", -- NORMAL mode prefix = "<leader>", buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings silent = true, -- use `silent` when creating keymaps noremap = true, -- use `noremap` when creating keymaps nowait = false -- use `nowait` when creating keymaps } --> SET MAPPINGS local mappings = { -- STANDARD MAPPINGS [";"] = " DASHBOARD", ["/"] = " COMMENT", ["e"] = "פּ EXPLORER", ["h"] = "ײַ HORIZONTAL SPLIT", ["q"] = " QUIT", ["s"] = " SAVE", ["t"] = " TERMINAL", ["v"] = "ﬠ VERTICAL SPLIT", ["w"] = " CLOSE BUFFER", -- MENUS l = { name = "ﭧ LSP", a = {"<cmd>lua require('telescope.builtin').lsp_code_actions(require('telescope.themes').get_cursor())<cr>", " CODE ACTIONS"}, d = {"<cmd>Telescope diagnostics buffnr=0<cr>", " DOCUMENT DIAGNOSTICS"}, D = {"<cmd>Telescope diagnostics<cr>", " WORKSPACE DIAGNOSTICS"}, f = {"<cmd>FormatWrite<cr>", " FORMAT"}, i = {"<cmd>LspInfo<cr>", " INFO"}, m = { name = " MARKDOWN", c = {"<cmd>TexCompile<cr>", " COMPILE"}, l = {"<cmd>TexViewer<cr>", " LATEX PREVIEW"}, p = {"<cmd>Glow<cr>", " MARKDOWN PREVIEW"}, }, -- QUICKFIX NOT YET WORKING q = {"<cmd>Telescope quickfix<cr>", " Quickfix"}, x = {"<cmd>cclose<cr>", " Close Quickfix"}, }, f = { name = " FIND", f = {"<cmd>lua require('telescope.builtin').find_files(require('plugins.telescope').custom_theme)<cr>", " FILE"}, m = {"<cmd>Telescope marks<cr>", " MARKS"}, M = {"<cmd>Telescope man_pages<cr>", " MAN PAGES"}, p = {"<cmd>Telescope projects<cr>", " PROJECTS"}, r = {"<cmd>Telescope oldfiles<cr>", " RECENT FILES"}, R = {"<cmd>Telescope registers<cr>", " REGISTERS"}, t = {"<cmd>Telescope live_grep<cr>", " TEXT"}, }, c = { name = "漣CONFIG", c = {"<cmd>PackerCompile<cr>", " COMPILE"}, p = {"<cmd>PackerProfile<cr>", " PROFILE"}, s = {"<cmd>PackerSync<cr>", "痢 SYNC"}, t = {"<cmd>Telescope colorscheme<cr>", " THEME"}, }, g = { name = " GIT", b = {"<cmd>Telescope git_branches<cr>", " BRANCHES"}, l = {"<cmd>lua_lazygit_toggle()<cr>", " LAZYGIT"}, }, d = { name = " DEBUG", b = {"<cmd>lua require'dap'.toggle_breakpoint()<cr>", " BREAKPOINT"}, c = {"<cmd>lua require'dap'.continue()<cr>", " CONTINUE"}, h = {"<cmd>help dap-api<cr>", " HELP"}, i = {"<cmd>lua require'dap'.step_into()<cr>", " STEP INTO"}, k = {"<cmd>help dap-mapping<cr>", " KEYBINDS"}, o = {"<cmd>lua require'dap'.step_over()<cr>", " STEP OVER"}, s = {"<cmd>lua require'dap'.repl.open()<cr>", " INSPECT STATE"}, }, } --> APPLY MAPPINGS AND OPTIONS local wk = require("which-key") wk.register(mappings, opts)
-- --[[ ---> 用于将当前插件提供为具体系统的上下文 -------------------------------------------------------------------------- ---> 参考文献如下 -----> / ----------------------------------------------------------------------------------------------------------------- --[[ ---> 统一函数指针 --]] -------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------- --[[ ---> 统一引用导入APP-LIBS --]] -------------------------------------------------------------------------- -----> 基础库引用 local p_base = require("app.plugins.handler_adapter") -------------------------------------------------------------------------- --[[ ---> 当前对象 --]] local handler = p_base:extend() ----------------------------------------------------------------------------------------------------------------- --[[ ---> 实例构造器 ------> 子类构造器中,必须实现 handler.super.new(self, name) --]] function handler:new(conf, store) -- 优先级调控 self.PRIORITY = 2 -- 插件名称 self._source = "divide" -- 传导至父类填充基类操作对象 handler.super.new(self, conf, store) end ----------------------------------------------------------------------------------------------------------------- function handler:_rewrite_action(rule, variables, conditions_matched) local ngx_var = ngx.var local ngx_var_uri = ngx_var.uri local ngx_var_host = ngx_var.host local micro_handle = self:combine_micro_handle_by_rule(rule, variables) local upstream_url = micro_handle.url if upstream_url then if self.utils.object.check(micro_handle.host) then ngx_var.upstream_host = micro_handle.host end ngx_var.upstream_url = micro_handle.url self:rule_log_info(rule, self.format("[%s-%s] take upstream host: %s, url: %s. host: %s, uri: %s", self._name, rule.name, ngx_var.upstream_host, ngx_var.upstream_url, ngx_var_host, ngx_var_uri)) else self:rule_log_err(rule, self.format("[%s-%s] no upstream host or url. host: %s, uri: %s", self._name, rule.name, ngx_var_host, ngx_var_uri)) end end ----------------------------------------------------------------------------------------------------------------- function handler:rewrite() self:exec_action(self._rewrite_action) end ----------------------------------------------------------------------------------------------------------------- return handler
---@module WeaponAmmoBase 枪械模块:枪械子弹基类 ---@copyright Lilith Games, Avatar Team ---@author Sharif Ma local WeaponAmmoBase = class('WeaponAmmoBase') ---WeaponAmmoBase类的构造函数 ---@param _id number 子弹ID ---@param _count number 拾取的数量 ---@param _character PlayerInstance 拾取的玩家 function WeaponAmmoBase:initialize(_id, _count, _character) self.id = _id self.order = GunConfig.AmmoConfig[self.id].Order self.pickSound = GunConfig.AmmoConfig[self.id].PickSound self.count = _count self.character = _character self:PickSound() end ---玩家拾取一定数量的子弹 function WeaponAmmoBase:PlayerPickAmmo(_weaponAmmo, _count) if _weaponAmmo then if _count >= _weaponAmmo.Count.Value then _count = _weaponAmmo.Count.Value world.S_Event.DestroyAmmoEvent:Fire(_weaponAmmo) else _weaponAmmo.Count.Value = _weaponAmmo.Count.Value - _count end end self.count = self.count + _count self:PickSound() end ---玩家丢弃一定数量的子弹 ---@param _count number 丢弃子弹的数量 function WeaponAmmoBase:PlayerDropAmmo(_count) local isDroppedAll = false if self.count <= 0 then return end if _count >= self.count then ---丢弃了所有的子弹 _count = self.count world.S_Event.CreateAmmoEvent:Fire(self.id, _count, self.character.Position) world.S_Event.PlayerPickAmmoEvent:Fire(localPlayer, {[self.id] = -_count}) isDroppedAll = true else ---丢弃部分子弹 world.S_Event.CreateAmmoEvent:Fire(self.id, _count, self.character.Position) world.S_Event.PlayerPickAmmoEvent:Fire(localPlayer, {[self.id] = -_count}) end self.count = self.count - _count return isDroppedAll end ---玩家换弹消耗一定数量的子弹 ---@param _count number 消耗子弹的数量 ---@return number 返回真正消耗的子弹数量 function WeaponAmmoBase:PlayerConsumeAmmo(_count) if self.count <= 0 then self.count = 0 return 0 end if _count >= self.count then _count = self.count end self.count = self.count - _count return _count end ---直接设置子弹数量为指定值 function WeaponAmmoBase:SetCount(_count) self.count = _count end ---析构函数 function WeaponAmmoBase:Destructor() self.count = nil self.id = nil ClearTable(self) self = nil end function WeaponAmmoBase:PickSound() local audio = world:CreateInstance('AudioSource', 'Audio_' .. self.pickSound, world.CurrentCamera) audio.LocalPosition = Vector3.Zero audio.SoundClip = ResourceManager.GetSoundClip('WeaponPackage/Audio/' .. self.pickSound) audio.Volume = 60 audio.MaxDistance = 30 audio.MinDistance = 30 audio.Loop = false audio.Doppler = 0 audio:Play() invoke( function() if audio then audio:Destroy() end end, 2 ) end return WeaponAmmoBase
------------ CONFIGURATION ---------------- -- set this to false if you do not want to enable automatic "recharging" TUNING.CONEMISSILE_REEQUIP = true ------------------------------------------- PrefabFiles = { "conemissile", } STRINGS = GLOBAL.STRINGS RECIPETABS = GLOBAL.RECIPETABS Recipe = GLOBAL.Recipe Ingredient = GLOBAL.Ingredient TECH = GLOBAL.TECH STRINGS.NAMES.CONEMISSILE = "Cone Missile" STRINGS.RECIPE_DESC.CONEMISSILE = "Neither sharp, nor streamlined." STRINGS.CHARACTERS.GENERIC.DESCRIBE.CONEMISSILE = "Monsters flee spotting the holy cone weapons!" local conemissile = GLOBAL.Recipe("conemissile",{ Ingredient("pinecone", 1) }, RECIPETABS.WAR, TECH.NONE ) conemissile.atlas = "images/inventoryimages/conemissile.xml" -- onhit damage TUNING.CONEMISSILE_DAMAGE = 12 -- projectile speed TUNING.CONEMISSILE_SPEED = 30 -- max throw distance TUNING.CONEMISSILE_DISTANCE = 5 -- missing chance TUNING.CONEMISSILE_MISS_PERCENT = 0.2 -- reloot chance -- every missed conemissile is going to drop (reloot). All in all reloot chance is: ALL_RELOOT_PERCENT = MISS_PERCENT + (1-MISS_PERCENT)*RELOOT_PERCENT (default(20%, 60%) = 68%) TUNING.CONEMISSILE_RELOOT_PERCENT = 0.6 -- how many conemissiles can be on one inventory slot TUNING.CONEMISSILE_STACK_SIZE = 5 -- pinecone time to regrow on evergreens TUNING.CONE_REGROW_TIME = TUNING.TOTAL_DAY_TIME * 5 -- extra pinecones! TUNING.EVERGREEN_EXTRA_PINECONE_PICK_PERCENT = 0.2 -- for balancing -- from .33, .15 TUNING.LEIF_PINECONE_CHILL_CHANCE_CLOSE = .2 TUNING.LEIF_PINECONE_CHILL_CHANCE_FAR = .075 -- from base=0.75*day_time TUNING.PINECONE_GROWTIME = {base=1*TUNING.TOTAL_DAY_TIME, random=0.25*TUNING.TOTAL_DAY_TIME} local function evergreenonpickedfn(inst, picker) if(math.random() <= TUNING.EVERGREEN_EXTRA_PINECONE_PICK_PERCENT) then inst.components.lootdropper:SpawnLootPrefab("pinecone") end end local function evergreenpostinit(inst) -- evergreens are pickable inst:AddComponent("pickable") -- sounds like picking up berries inst.components.pickable.picksound = "dontstarve/wilson/harvest_berries" -- find pinecones inst.components.pickable:SetUp("pinecone", TUNING.CONE_REGROW_TIME) inst.components.pickable.onpickedfn = evergreenonpickedfn inst.components.pickable.fertilizable = false if inst.components.growable.stage == 3 and inst.build ~= "sparse" then inst.components.pickable.canbepicked = true else inst.components.pickable.canbepicked = false end -- save current onfinish method for wrapper local onfinishfn = inst.components.workable.onfinish -- overwrite with wrapper inst.components.workable:SetOnFinishCallback( --wrapper function(inst, chopper) -- stumps dont have cones anymore inst.components.pickable.canbepicked = false onfinishfn(inst, chopper) end ) -- save current stage fn for wrapper local growtallfn = inst.components.growable.stages[3].fn -- overwrite with wrapper inst.components.growable.stages[3].fn = ( -- wrapper function(inst) -- trees growing tall sprout some cones if(inst.components.pickable ~= nil) then inst.components.pickable.canbepicked = true end growtallfn(inst) end ) -- save current stage fn for wrapper local growoldfn = inst.components.growable.stages[4].fn -- overwrite with wrapper inst.components.growable.stages[4].fn = ( -- wrapper function(inst) -- trees growing old dont have cones to farm anymore if(inst.components.pickable ~= nil) then inst.components.pickable.canbepicked = false end growoldfn(inst) end ) --[[if inst.components.burnable then -- save current stage fn for wrapper local onburntfn = inst.components.burnable.onburnt -- overwrite with wrapper inst.components.burnable:SetOnBurnt( -- wrapper function(inst) -- burned trees dont drop random pinecones anymore onburntfn(inst) end ) end]] end local function pineconepostinit(inst) -- pinecones burn with intensity located between tiny and small inst.components.fuel.fuelvalue = (TUNING.TINY_FUEL + TUNING.SMALL_FUEL)*0.5 end AddPrefabPostInit("evergreen", evergreenpostinit) AddPrefabPostInit("pinecone", pineconepostinit)
--- Utility functions for Restia -- @module restia.utils -- @author DarkWiiPlayer -- @license Unlicense local utils = {} local lfs = require 'lfs' local colors = require 'restia.colors' local escapes = { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['"'] = '&quot;', ["'"] = '&#039;', } do local buf = {} for char in pairs(escapes) do table.insert(buf, char) end escapes.pattern = "["..table.concat(buf).."]" end --- Escapes special HTML characters in a string function utils.escape(str) return (tostring(str):gsub(escapes.pattern, escapes)) end --- Makes a table look up missing keys with `require` function utils.deepmodule(prefix) return setmetatable({}, { __index = function(self, name) return require(prefix .. "." .. name) end }) end --- Mixes several tables into another and returns it. function utils.mixin(first, second, ...) if type(second)=="table" then for key, value in pairs(second) do if type(value) == "table" then if type(first[key]) ~= "table" then first[key] = {} end utils.mixin(first[key], value) else first[key] = value end end return utils.mixin(first, ...) else return first end end --- Removes excessive indentation from a block of text function utils.normalizeindent(block) local indent = '^'..(block:match("^%s+") or '') return (block:gsub('[^\n]+', function(line) return line:gsub(indent, ''):gsub('[\t ]+$', ''):gsub("^%s*$", '') end)) end --- Removes leading whitespace up to and including a pipe character. -- This is used to trim off unwanted whitespace at the beginning of a line. -- This is hopefully a bit faster and more versatile than the normalizeindent function. function utils.unpipe(block) return block:gsub('[^\n]+', function(line) return line:gsub('^%s*|', ''):gsub('^%s+$', '') end) end --- Indexes tables recursively with a chain of string keys function utils.deepindex(tab, path) if type(path)~="string" then return nil, "path is not a string" end local index, rest = path:match("^%.?([%a%d]+)(.*)") if not index then index, rest = path:match("^%[(%d+)%](.*)") index = tonumber(index) end if index then if #rest>0 then if tab[index] then return utils.deepindex(tab[index], rest) else return nil, "full path not present in table" end else return tab[index] end else return nil, "malformed index-path string" end end --- Inserts a table into a nested table following a path. -- The path string mimics normal chained indexing in normal Lua. -- Nil-elements along the path will be created as tables. -- Non-nil elements will be indexed and error accordingly if this fails. -- @tparam table tab A table or indexable object to recursively insert into -- @tparam table path A string describing the path to iterate -- @param value The value that will be inserted -- @usage -- utils.deepinsert(some_table, 'foo.bar.baz', value) function utils.deepinsert(tab, path, value) if type(path) == "table" then local current = tab for i=1,math.huge do local key = path[i] if path[i+1] then if not current[key] then current[key] = {} end current = current[key] else current[key] = value break end end return value or true elseif type(path) == "string" then local index, rest = path:match("^%.?([^%[%.]+)(.*)") if not index then index, rest = path:match("^%[(%d+)%](.*)") index = tonumber(index) end if index then if #rest>0 then local current if tab[index] then current = tab[index] else current = {} tab[index] = current end return utils.deepinsert(current, rest, value) else tab[index] = value return value or true end else return nil, "malformed index-path string: " .. path end else return nil, "path is neither string nor table: " .. type(path) end end --- Turns a flat table and turns it into a nested table. -- @usage -- local deep = restia.utils.deep { -- ['foo.bar.baz'] = "hello"; -- ['foo[1]'] = "first"; -- ['foo[2]'] = "second"; -- } -- -- Is equal to -- local deep = { -- foo = { -- "first", "second"; -- bar = { baz = "hello" }; -- } -- } function utils.deepen(tab) local deep = {} for path, value in pairs(tab) do if not utils.deepinsert(deep, path, value) then deep[path] = value end end return deep end utils.tree = {} --- Inserts a value into a tree. -- Every node in the tree, not only leaves, can hold a value. -- The special index __value is used for this and should not appear in the route. -- @tparam table head The tree to insert the value into. -- @tparam table route A list of values to recursively index the tree with. -- @param value Any Lua value to be inserted into the tree. -- @treturn table The head node of the tree. -- @see tree.get -- @usage -- local insert = restia.utils.tree.insert -- local tree = {} -- insert(tree, {"foo"}, "value 1") -- -- Nodes can have values and children at once -- insert(tree, {"foo", "bar"}, "value 2") -- -- Keys can be anything -- insert(tree, {function() end, {}}, "value 2") -- @function tree.insert function utils.tree.insert(head, route, value) local tail = head for i, key in ipairs(route) do local next = tail[key] if not next then next = {} tail[key] = next end tail = next end tail.__value = value return head end --- Gets a value from a tree. -- @tparam table head The tree to retreive the value from. -- @tparam table route A list of values to recursively index the tree with. -- @return The value at the described node in the tree. -- @see tree.insert -- @usage -- local tree = { foo = { bar = { __value = "Some value" }, __value = "Unused value" } } -- restia.utils.tree.get(tree, {"foo", "bar"}) -- @function tree.get function utils.tree.get(head, route) for i, key in ipairs(route) do head = head[key] if not head then return nil end end return head.__value end local function files(dir, func) for path in lfs.dir(dir) do if path:sub(1, 1) ~= '.' then local name = dir .. '/' .. path local mode = lfs.attributes(name, 'mode') if mode == 'directory' then files(name, func) elseif mode == 'file' then func(name) end end end end local function random(n) if n > 0 then return math.random(256)-1, random(n-1) end end --- Recursively concatenates a table function utils.deepconcat(tab, separator) for key, value in ipairs(tab) do if type(value)=="table" then tab[key]=utils.deepconcat(value, separator) else tab[key]=tostring(value) end end return table.concat(tab, separator) end --- Returns a list containing the result of `debug.getinfo` for every level in -- the current call stack. The table also contains its length at index `n`. function utils.stack(level) local stack = {} for i=level+1, math.huge do local info = debug.getinfo(i) if info then table.insert(stack, info) else stack.n = i break end end return stack end --- Returns a random hexadecimal string with N bytes function utils.randomhex(n) return string.format(string.rep("%03x", n), random(n)) end --- Returns an iterator over all the files in a directory and subdirectories -- @tparam string dir The directory to look in -- @tparam[opt] string filter A string to match filenames against for filtering -- @treturn function Iterator over the file names -- @usage -- for file in utils.files 'views' do -- print('found view: ', file) -- end -- -- for image in utils.files(".", "%.png$") do -- print('found image: ', image) -- end function utils.files(dir, filter) if type(filter)=="string" then return coroutine.wrap(files), dir, function(name) if name:find(filter) then coroutine.yield(name) end end else return coroutine.wrap(files), dir, coroutine.yield end end --- Deletes a file or directory recursively -- @tparam string path The path to the file or directory to delete function utils.delete(path) path = path:gsub('/+$', '') local mode = lfs.attributes(path, 'mode') if mode=='directory' then for entry in lfs.dir(path) do if not entry:match("^%.%.?$") then utils.delete(path..'/'..entry) end end end os.remove(path) end --- Converts a filesystem path to something deepinsert can handle function utils.fs2tab(path) if type(path)~="string" then error(debug.getinfo(1).name..": Expected string, got "..type(path), 2) end local elements = {} for element in path:gmatch("[^/]+") do if element == ".." and elements[1] then table.remove(elements) elseif element ~= "." then table.insert(elements, element) end end return elements end --- Reads a directory into a table function utils.readdir(path) local mode = lfs.attributes(path, 'mode') if mode == 'directory' then local result = {} for name in lfs.dir(path) do if name:sub(1, 1) ~= '.' then result[name] = utils.readdir(path.."/"..name) end end return result elseif mode == 'file' then return(io.open(path, 'rb'):read('a')) end end --- Copies a directory recursively function utils.copy(from, to) local mode = lfs.attributes(from, 'mode') if mode == 'directory' then lfs.mkdir(to) for path in lfs.dir(from) do if path:sub(1, 1) ~= '.' then utils.copy(from.."/"..path, to.."/"..path) end end elseif mode == 'file' then local of, err = io.open(to, 'wb') if not of then error(err) end of:write(io.open(from, 'rb'):read('a')) of:close() end end function utils.mkdir(path) local slash = 0 while slash do slash = path:find("/", slash+1) lfs.mkdir(path:sub(1, slash)) end end --- Builds a directory structure recursively from a table template. -- @tparam string prefix A prefix to the path, aka. where to initialize the directory structure. -- @tparam table tab A table representing the directory structure. -- Table entries are subdirectories, strings are files, false means delete, true means touch file, everything else is an error. -- @usage -- builddir { -- sub_dir = { -- empty_file = '' -- } -- file = 'Hello World!'; -- } -- @todo add `true` option for empty file -- @todo add `false` option to delete existing files/directories function utils.builddir(prefix, tab) if lfs.attributes(prefix, 'mode') ~= "directory" then print("Root " ..colors.red(prefix)) utils.mkdir(prefix) end if not tab then tab = prefix prefix = '.' end if not type(tab) == 'table' then error("Invalid argument; expected table, got "..type(tab), 1) end for path, value in pairs(tab) do if prefix then path = prefix.."/"..tostring(path) end if type(value) == "table" then if lfs.attributes(path, 'mode') ~= "directory" then print ("Directory "..colors.blue(path)) local result, err = lfs.mkdir(path) if not result then error("Building "..path..":"..err) end else print(colors.dim_white("Directory "..path)) end utils.builddir(path, value) elseif type(value) == "string" then print( "File " ..colors.magenta(path) .." with " ..#value .." bytes" ) local file = assert(io.open(path,'w')) file:write(value) file:close() elseif value==false then print( "Deleting "..colors.red(path) ) utils.delete(path) elseif value==true then print( "Touching "..colors.yellow(path) ) local file = io.open(path) if not file then file = io.open(path, 'w') file:write('') end file:close() else print( "Unknown type at " ..colors.red(path) .." (" ..colors.red(type(value)) ..")" ) end end end function utils.frontmatter(text) local a, b = text:find('^%-%-%-+\n') local c, d = text:find('\n%-%-%-+\n', b) if b and c then return text:sub(b+1, c-1), text:sub(d+1, -1) else return nil, text end end return utils
local Tunnel = module("vrp", "lib/Tunnel") local Proxy = module("vrp", "lib/Proxy") vRPani = {} vRP = Proxy.getInterface("vRP") vRPclient = Tunnel.getInterface("vRP","vrp_attitudes") BMclient = Tunnel.getInterface("vrp_attitudes","vrp_attitudes") vRPani = Tunnel.getInterface("vrp_attitudes","vrp_attitudes") Tunnel.bindInterface("vrp_attitudes",vRPani) local Lang = module("vrp", "lib/Lang") local cfg = module("vrp", "cfg/base") -- REMEMBER TO ADD THE PERMISSIONS FOR WHAT YOU WANT TO USE -- CREATES PLAYER SUBMENU AND ADD CHOICES local ch_animation_menu = {function(player,choice) local user_id = vRP.getUserId({player}) local menu = {} menu.name = "Gågange" menu.css = {top = "75px", header_color = "rgba(0,0,255,0.75)"} menu.onclose = function(player) vRP.openMainMenu({player}) end -- nest menu menu[">Stop"] = {function(player,choice) vRPani.resetMovement(player,{false}) end} menu["Normal Mand"] = {function(player,choice) vRPani.playMovement(player, {"move_m@confident",true,true,false,false}) end} menu["Normal Kvinde"] = {function(player,choice) vRPani.playMovement(player, {"move_f@heels@c",true,true,false,false}) end} menu["Depressiv Mand"] = {function(player,choice) vRPani.playMovement(player, {"move_m@depressed@a",true,true,false,false}) end} menu["Depressiv Kvinde"] = {function(player,choice) vRPani.playMovement(player, {"move_f@depressed@a",true,true,false,false}) end} menu["Forretning"] = {function(player,choice) vRPani.playMovement(player, {"move_m@business@a",true,true,false,false}) end} menu["Bestemme"] = {function(player,choice) vRPani.playMovement(player, {"move_m@brave@a",true,true,false,false}) end} menu["Casual"] = {function(player,choice) vRPani.playMovement(player, {"move_m@casual@a",true,true,false,false}) end} menu["Tyk"] = {function(player,choice) vRPani.playMovement(player, {"move_m@fat@a",true,true,false,false}) end} menu["Hippi"] = {function(player,choice) vRPani.playMovement(player, {"move_m@hipster@a",true,true,false,false}) end} menu["Såret"] = {function(player,choice) vRPani.playMovement(player, {"move_m@injured",true,true,false,false}) end} menu["Nervøs"] = {function(player,choice) vRPani.playMovement(player, {"move_m@hurry@a",true,true,false,false}) end} menu["Hobo"] = {function(player,choice) vRPani.playMovement(player, {"move_m@hobo@a",true,true,false,false}) end} menu["Ulykkelig"] = {function(player,choice) vRPani.playMovement(player, {"move_m@sad@a",true,true,false,false}) end} menu["Muskel"] = {function(player,choice) vRPani.playMovement(player, {"move_m@muscle@a",true,true,false,false}) end} menu["Gangster"] = {function(player,choice) vRPani.playMovement(player, {"move_m@shadyped@a",true,true,false,false}) end} menu["Træthed"] = {function(player,choice) vRPani.playMovement(player, {"move_m@buzzed",true,true,false,false}) end} menu["Fuld/Træt"] = {function(player,choice) vRPani.playMovement(player, {"move_m@buzzed",true,true,false,false}) end} menu["Presset"] = {function(player,choice) vRPani.playMovement(player, {"move_m@hurry_butch@a",true,true,false,false}) end} menu["Voldsom"] = {function(player,choice) vRPani.playMovement(player, {"move_m@money",true,true,false,false}) end} menu["Lunte"] = {function(player,choice) vRPani.playMovement(player, {"move_m@quick",true,true,false,false}) end} menu["Homoseksuel"] = {function(player,choice) vRPani.playMovement(player, {"move_f@maneater",true,true,false,false}) end} menu["Uforskammet"] = {function(player,choice) vRPani.playMovement(player, {"move_f@sassy",true,true,false,false}) end} menu["Diva"] = {function(player,choice) vRPani.playMovement(player, {"move_f@arrogant@a",true,true,false,false}) end} vRP.openMenu({player, menu}) end} -- REGISTER MAIN MENU CHOICES vRP.registerMenuBuilder({"main", function(add, data) local user_id = vRP.getUserId({data.player}) if user_id ~= nil then local choices = {} choices["Bevægelse"] = ch_animation_menu -- opens player submenu add(choices) end end})
local trimstring = require 'trimstring' local t = require 'testhelper' t( trimstring(''), '' ) t( trimstring('a'), 'a' ) t( trimstring(' a'), 'a' ) t( trimstring('a '), 'a' ) t( trimstring(' a '), 'a' ) t( trimstring(' a a'), 'a a' ) t( trimstring('a a '), 'a a' ) t( trimstring(' a a '), 'a a' ) t( trimstring(' \nstr\r\t '), 'str' ) t.test_embedded_example() t()
return { Name = "to"; Description = "Teleports you to another player."; Group = "DefaultDebug"; Args = { { Type = "player"; Name = "target"; Description = "The player to teleport to." } }; }
chats = {} function dl_cb (arg, data) var_dump(arg) var_dump(data) end function tdcli_update_callback (data) var_dump(data) if (data.ID == "UpdateNewMessage") then local msg = data.message_ local d = data.disable_notification_ local chat = chats[msg.chat_id_] if ((not d) and chat) then if msg.content_.ID == "MessageText" then var_dump (chat.title_, msg.content_.text_) else var_dump (chat.title_, msg.content_.ID) end end if msg.content_.ID == "MessageText" then if msg.content_.text_ == "ping" then tdcli_function ({ID="SendMessage", chat_id_=msg.chat_id_, reply_to_message_id_=msg.id_, disable_notification_=0, from_background_=1, reply_markup_=nil, input_message_content_={ID="InputMessageText", text_="pong", disable_web_page_preview_=1, clear_draft_=0, entities_={}}}) elseif msg.content_.text_ == "PING" then tdcli_function ({ID="SendMessage", chat_id_=msg.chat_id_, reply_to_message_id_=msg.id_, disable_notification_=0, from_background_=1, reply_markup_=nil, input_message_content_={ID="InputMessageText", text_="pong", disable_web_page_preview_=1, clear_draft_=0, entities_={[0]={ID="MessageEntityBold", offset_=0, length_=4}}}}) end end elseif (data.ID == "UpdateChat") then chat = data.chat_ chats[chat.id_] = chat elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, nil, nil) end end
--------------------------------------------------------------------------------------------- -- Issue https://github.com/SmartDeviceLink/sdl_core/issues/995 --------------------------------------------------------------------------------------------- -- Preconditions: -- 1. Core, HMI started. -- 2. App is registered on HMI and has HMI level BACKGROUND -- Steps to reproduce: -- 1. Register app via 4th protocol. -- 2. App sends incorrect json on SystemRequest and receives error code in response. -- 3. Bring app to background and then to foreground again or register new app via 4th protocol. -- Expected result: -- SDL does not send OnSystemRequest(QUERY_APPS) to the same app after bringing it to foreground -- and also to new registered app after unsuccessful attempt to send query json. --------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require("user_modules/sequences/actions") local utils = require("user_modules/utils") --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false config.defaultProtocolVersion = 4 -- Set 4 protocol as default for script --[[ Local Variables ]] config.application1.registerAppInterfaceParams.appHMIType = { "MEDIA" } config.application1.registerAppInterfaceParams.isMediaApplication = true config.application1.registerAppInterfaceParams.syncMsgVersion.majorVersion = 4 --Sending OnHMIStatus notification form mobile application local function SendingOnHMIStatusFromMobile(pAppId, pLevel) local sessionName = common.getMobileSession(pAppId) sessionName.correlationId = sessionName.correlationId + 100*pAppId local msg = { serviceType = 7, frameInfo = 0, rpcType = 2, rpcFunctionId = 32768, rpcCorrelationId = sessionName.correlationId, payload = '{"hmiLevel" : "' .. tostring(pLevel) .. '"' .. ', "audioStreamingState" : "NOT_AUDIBLE"' .. ', "systemContext" : "MAIN"' .. ', "videoStreamingState" : "NOT_STREAMABLE"}' } sessionName:Send(msg) utils.cprint(33, "Sending OnHMIStatus from mobile app" .. pAppId .. " with level ".. tostring(pLevel)) end local function OnSystemRequest_QueryApps_IsError() SendingOnHMIStatusFromMobile(1, "FULL") common.getMobileSession(1):ExpectNotification("OnSystemRequest", { requestType = "QUERY_APPS" }) :Do(function() local cid = common.getMobileSession(1):SendRPC("SystemRequest", { requestType = "QUERY_APPS", fileName = "incorrectJSON.json" }, "files/jsons/QUERRY_jsons/incorrectJSON.json") common.getMobileSession(1):ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" }) end) end local function RegisterSecondApp() common.registerApp(2) end local function OnSystemRequest_QueryApps_IsNotSentToNewRegisteredApp() SendingOnHMIStatusFromMobile(1, "BACKGROUND") SendingOnHMIStatusFromMobile(2, "FULL") common.getMobileSession(2):ExpectNotification("OnSystemRequest", { requestType = "QUERY_APPS" }) :Times(0) common.getMobileSession(1):ExpectNotification("OnSystemRequest", { requestType = "QUERY_APPS" }) :Times(0) end local function OnSystemRequest_QueryApps_IsNotSentToTheSameAppInForeground() SendingOnHMIStatusFromMobile(2, "BACKGROUND") SendingOnHMIStatusFromMobile(1, "FULL") common.getMobileSession(2):ExpectNotification("OnSystemRequest", { requestType = "QUERY_APPS" }) :Times(0) common.getMobileSession(1):ExpectNotification("OnSystemRequest", { requestType = "QUERY_APPS" }) :Times(0) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register app1", common.registerAppWOPTU) runner.Step("Activate app1", common.activateApp) runner.Title("Test") runner.Step("OnSystemRequest_QueryApps_IsError", OnSystemRequest_QueryApps_IsError) runner.Step("Register app2", RegisterSecondApp) runner.Step("OnSystemRequest_QueryApps_IsNotSentToNewRegisteredApp", OnSystemRequest_QueryApps_IsNotSentToNewRegisteredApp) runner.Step("OnSystemRequest_QueryApps_IsNotSentToTheSameAppInForeground", OnSystemRequest_QueryApps_IsNotSentToTheSameAppInForeground) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
local len = table.maxn Node = class() -- attributes: -- changed: has changed since last iteration -- wp, rp: write and read protection -- aa: argument alias information -- tl: thread-local bags (that do not need protection) -- assign: assignment information -- writes, reads: which variables are being read/written -- pred, succ: lists of predecessors and successors -- ast: abstract syntax tree of statement/expression. Graph = class() -- Attributes: -- nodes: list of all nodes -- start: entry node function Graph:create(nodes, start) self.nodes = nodes or { } self.start = start end function Node:create(ast) self.ast = ast self.pred = { } self.succ = { } end function list_errors(graph, accessproperty, guardproperty) local nodes = graph.nodes local errors = { } for i = 1, #nodes do local node = nodes[i] local accesses = node[accessproperty] local guards = node[guardproperty] for j = 1, #accesses do local varname, pos = unpack(accesses) if not guards[varname] then push(errors, pos) end end end return errors end local function intersection(lists) local n = #lists if n == 0 then return { } elseif n == 1 then local result = { } local list = lists[1] for i = 1, len(list) do result[i] = list[i] end return result else local result = { } local list = lists[1] for j = 1, len(list) do if list[j] then local r = true for i = 2, n do r = r and lists[i][j] end result[j] = r end end return result end end local function assignments(input, node) local output = { } for var = 1, len(input) do if input[var] then if not node.assignto[var] then output[var] = true elseif node.assignfrom[var] then output[node.assignfrom[var]] = true end end end return output end -- The trans_?? functions transfer semantic information relating -- to rp, wp, and tl properties from node inputs to node outputs. local function trans_rp(input, node) local rg = node.rg local wg = node.wg local rg2 = node.add_rg local wg2 = node.add_wg for i = 1, #rg do input[rg[i]] = true end for i = 1, #wg do input[wg[i]] = true end if rg2 then for i = 1, #rg2 do input[rg2[i]] = true end end if wg2 then for i = 1, #wg2 do input[wg2[i]] = true end end local r = assignments(input, node) return r end local function trans_wp(input, node) local wg = node.wg local wg2 = node.add_wg for i = 1, #wg do input[wg[i]] = true end if wg2 then for i = 1, #wg2 do input[wg2[i]] = true end end return assignments(input, node) end local function trans_tl(input, node) local newbags = node.newbags local result = assignments(input, node) for i = 1, #newbags do result[newbags[i]] = true end return result end local function standard_changed_from(new, old) -- this relies on sets growing monotonically if not old then return true end for i = 1, len(new) do if new[i] and not old[i] then return true end end return false end local function join_aa(preds) local result = { } for i = 1, #preds do local pred = preds[i] for var = 1, len(pred) do map = pred[var] if map then if not result[var] then result[var] = clone(map) else for var2, _ in map do result[var][var2] = true end end end end end return result end local function trans_aa(input, node) local result = { } for var = 1, len(input) do map = input[var] if map then result[var] = assignments(map, node) end end return result end -- dataflow analysis relies on a transfer and a join function. It computes -- the smallest fixpoint such that for each node, the transfer function -- maps input to output values and the join function maps the outputs of -- all predecessors of a node to its input. local function forward_dataflow(graph, input, output, trans, join, changed_from) local nodes = graph.nodes local changed for i = 1, #nodes do nodes[i].changed = true end repeat changed = false for i = 1, #nodes do local node = nodes[i] local node_changed if true then local preds, newinput, newoutput node.changed = false preds = { } for _, pred in ipairs(node.pred) do push(preds, pred[output]) end newinput = join(preds, node) newoutput = trans(clone(newinput), node) if changed_from(newinput, node[input]) then node[input] = newinput node_changed = true changed = true end if changed_from(newoutput, node[output]) then node[output] = newoutput node_changed = true changed = true end if node_changed then for _, succ in ipairs(node.succ) do succ.changed = true end end end end until not changed end local function make_unique(list) local mem = { } local p = 1 for i = 1, #list, 2 do local item = list[i] if not mem[item] then mem[item] = true list[p] = list[i] list[p+1] = list[i+1] p = p + 2 end end -- delete trailing entries for i = p, #list do list[i] = nil end end local pass1 = true local function init_properties(node) local ast = node.ast node.changed = false node.aain = { } node.newbags = { } node.aaout = { } node.tlin = { } node.tlout = { } node.wpin = { } node.rpin = { } node.wpout = { } node.rpout = { } node.wg = { } node.rg = { } node.writes = { } node.reads = { } node.assign = { } node.assignto = { } node.assignfrom = { } if ast then if pass1 then ast:fix_types() end ast:track_aliases_and_guards(node.assign, node.wg, node.rg) ast:track_thread_locals(node.newbags) for _, pair in ipairs(node.assign) do node.assignto[pair[1]] = true if pair[2] then node.assignfrom[pair[2]] = pair[1] end end ast:bag_access(node.reads, node.writes, node.reads, node.writes, 0) make_unique(node.reads) make_unique(node.writes) end end local function dataflow_pass(funcdef) local graph = funcdef.graph local nodes = graph.nodes local start = graph.start for i = 1, #nodes do local node = nodes[i] init_properties(node) end local aa = { } for i = 1, #funcdef.args do aa[i] = { } aa[i][i] = true end start.aain = aa forward_dataflow(graph, "wpin", "wpout", trans_wp, intersection, standard_changed_from) forward_dataflow(graph, "rpin", "rpout", trans_rp, intersection, standard_changed_from) forward_dataflow(graph, "tlin", "tlout", trans_tl, intersection, standard_changed_from) forward_dataflow(graph, "aain", "aaout", trans_aa, join_aa, standard_changed_from) end local function suggest(funcdef, node, mode, varname) if not node.start_pos then return end local sourcefile, sourceline = find_source_position(funcdef.source_file_input, node.start_pos, funcdef.source_file_mapping) local is_start = is_line_start(funcdef.source_file_input, node.start_pos) if node.insertion_point == node and is_start then -- prefix guard print(string.format("%s:%d:%s:%s", sourcefile, sourceline, mode, varname)) else local _, finish_line = find_source_position(funcdef.source_file_input, node.finish_pos, funcdef.source_file_mapping) -- inline guard print(string.format("%s:%d-%d:%s:%s", sourcefile, sourceline, finish_line, mode, varname)) end end local function add_guards(funcdef) local graph = funcdef.graph local nodes = graph.nodes local start = graph.start for i = 1, #nodes do local node = nodes[i] init_properties(node) node.add_wg = { } node.add_rg = { } end local aa = { } for i = 1, #funcdef.args do if funcdef.arg_writes[i] then push(start.add_wg, i) push(start.wg, i) push(start.wpin, i) elseif funcdef.arg_reads[i] then push(start.add_rg, i) push(start.rg, i) push(start.rpin, i) end end local errors repeat errors = false forward_dataflow(graph, "wpin", "wpout", trans_wp, intersection, standard_changed_from) forward_dataflow(graph, "rpin", "rpout", trans_rp, intersection, standard_changed_from) forward_dataflow(graph, "tlin", "tlout", trans_tl, intersection, standard_changed_from) for i = 1, #nodes do local node = nodes[i] for j = 1, #node.writes, 2 do local var = node.writes[j] if not node.wpin[var] and not node.tlin[var] then local insertion_point = node.insertion_point push(node.add_wg, var) node.wpin[var] = true errors = true break end end if errors then break end for j = 1, #node.reads, 2 do local var = node.reads[j] if not node.rpin[var] and not node.tlin[var] then local insertion_point = node.insertion_point push(node.add_rg, var) node.rpin[var] = true errors = true break end end if errors then break end end until not errors for i = 1, #nodes do local node = nodes[i] local guarded = { } for _, var in ipairs(node.add_wg) do if not guarded[var] and node.local_vars[var][2]:bag()==0 then suggest(funcdef, node, "W", node.local_vars[var][1]) guarded[var] = true end end for _, var in ipairs(node.add_rg) do if not guarded[var] and node.local_vars[var][2]:bag()==0 then suggest(funcdef, node, "R", node.local_vars[var][1]) guarded[var] = true end end end end local function check_argument_accesses(funcdef) local graph = funcdef.graph local nodes = graph.nodes local reads = { } local writes = { } for i = 1, #nodes do local node = nodes[i] for arg = 1, len(node.aain) do map = node.aain[arg] if map then for j = 1, #node.writes, 2 do local var = node.writes[j] if map[var] and not node.tlin[var] and not node.wpin[var] then writes[arg] = true end end for j = 1, #node.reads, 2 do local var = node.reads[j] if map[var] and not node.tlin[var] and not node.rpin[var] then reads[arg] = true end end end end funcdef.arg_writes = writes funcdef.arg_reads = reads end end local function checkerrors(funcdef) local graph = funcdef.graph local nodes = graph.nodes for i = 1, #nodes do local node = nodes[i] for j = 1, #node.writes, 2 do local var = node.writes[j] if not node.wpin[var] and not node.tlin[var] then show_error(funcdef.source_file_input, funcdef.source_file_mapping, node.writes[j+1], "Unprotected write of '".. node.local_vars[var][1] .."'") end end for j = 1, #node.reads, 2 do local var = node.reads[j] if not node.rpin[var] and not node.tlin[var] then show_error(funcdef.source_file_input, funcdef.source_file_mapping, node.reads[j+1], "Unprotected read of '".. node.local_vars[var][1] .."'") end end end end function run_dataflow_analysis() for _, funcdef in ipairs(all_functions) do dataflow_pass(funcdef) end pass1 = false for i = 2, options.pass_count do for _, funcdef in ipairs(all_functions) do check_argument_accesses(funcdef) end for _, funcdef in ipairs(all_functions) do dataflow_pass(funcdef) end end if options.report_type == "errors" then for _, funcdef in ipairs(entry_points) do checkerrors(funcdef) end elseif options.report_type == "suggestions" then for _, funcdef in ipairs(all_functions) do add_guards(funcdef) end else system_error("Unknown report type") end end function dump(funcdef) local nodes = funcdef.graph.nodes for i = 1, #nodes do local node = nodes[i] pp({ index = node.index, rpin = node.rpin, rpout = node.rpout, rg = node.rg, reads = node.reads, succ = map(node.succ, function(n) return n.index end) }) end end
local win = window.new("Run Program",nil,40) do win:setResizable(false) local inputBox = UIElement.UITextbox.new(win,nil,20) inputBox:focusOn() inputBox:setCallback(function(keyIn) if love.filesystem.isFile("progs/"..keyIn) then local ok, chunk, result ok, chunk = pcall( love.filesystem.load, "progs/"..keyIn ) -- load the chunk safely if not ok then ok=tostring(ok) print(ok..'| The following error happend: ' .. tostring(chunk)) love.filesystem.load("ewin.lua")(ok.."| Error: "..tostring(chunk)) else ok, result = pcall(chunk) -- execute the chunk safely if not ok then -- will be false if there is an error ok=tostring(ok) print(ok..'| The following error happened: ' .. tostring(result)) love.filesystem.load("ewin.lua")(ok.."| Error: "..tostring(result)) else print('The result of loading is: ' .. tostring(result)) end end else if love.filesystem.isDirectory("progs/"..keyIn) then love.filesystem.load("ewin.lua")("Error: progs/"..keyIn.." is a directory!") else love.filesystem.load("ewin.lua")("Error: progs/"..keyIn.." does not exist!") end end win.close() end) win.callbacks.exit = function() inputBox:exit() end win.callbacks.draw = function() --TODO --print("CALLED!") win:setBackgroundColor(250,250,250) love.graphics.setColor(0,0,0,255) love.graphics.print("Type the name of a program to open:",3,3) inputBox:draw() end end win:setVisible(true) --"cmd": ["C:\\LOVE\\love.exe", "C:\\Users\\Bryan\\Documents\\TIGM"]
-- Declare all of the components local components = {} components.position = function(entity, x, y) entity.position = { x = x, y = y } end components.movementDirection = function(entity, x, y) entity.movementDirection = { x = x, y = y } end components.dimensions = function(entity, w, h) entity.dimensions = { w = w, h = h } end components.rotation = function(entity, r) entity.rotation = r end components.speed = function(entity, speed) entity.speed = { cur = speed, max = speed } end components.health = function(entity, health) entity.health = { cur = health, max = health } end components.dead = function(entity) entity.dead = true end components.showHealth = function(entity) entity.showHealth = true end components.showBigHealth = function(entity, pos, name) entity.showBigHealth = { pos = pos, name = name } end components.drawable = function(entity, image) entity.drawable = image end components.keyboardControl = function(entity) entity.keyboardControl = true end components.wandererAI = function(entity) entity.wandererAI = true end components.mouseLook = function(entity) entity.mouseLook = true end components.playerFollowAI = function(entity) entity.playerFollowAI = true end components.chargeAI = function(entity) entity.chargeAI = { charging = false } end components.enterArenaAI = function(entity) entity.enterArenaAI = true end components.shootFireAI = function(entity, cd) entity.shootFireAI = { cd = { cur = 0, max = cd } } end components.playerCast = function(entity) entity.playerCast = { bloodBullet = { cd = { cur = 0.0, max = 0.1 }, cost = 1, fireFunc = function() return love.mouse.isDown(1) end, castFunc = function() return 1 end }, bloodSuck = { cd = { cur = 0.0, max = 0.5 }, cost = 0, fireFunc = function() return love.mouse.isDown(2) end, castFunc = function() return 2 end }, convert = { cd = { cur = 0, max = 10 }, cost = 50, fireFunc = function() return love.keyboard.isDown("space") end, castFunc = function() return 3 end } } end components.hurtPlayerOnTouch = function(entity, value) entity.hurtPlayerOnTouch = value end components.hurtEnemyOnTouch = function(entity, value) entity.hurtEnemyOnTouch = value end components.dieOnCollision = function(entity) entity.dieOnCollision = true end components.giveHealthOnTouch = function(entity, value) entity.giveHealthOnTouch = value end components.damageCircle = function(entity, r) entity.damageCircle = r end components.collideWithRoom = function(entity) entity.collideWithRoom = true end components.killIfOutsideOfRoom = function(entity) entity.killIfOutsideOfRoom = true end components.killAfterDelay = function(entity, delay) entity.killAfterDelay = delay end components.player = function(entity) entity.player = true end components.enemy = function(entity) entity.enemy = true end components.convertOnDeath = function(entity) entity.convertOnDeath = true end components.takeConstantDamage = function(entity, value) entity.takeConstantDamage = value end components.stopMovementAfter = function(entity, delay) entity.stopMovementAfter = delay end return components
local datasets = require 'dataset-init' local Threads = require 'threads' Threads.serialization('threads.sharedserialize') local M = {} local DataLoader = torch.class('DataLoader', M) function DataLoader.getDataFaces(opt, split) print('=> Building dataset...') base_dir = opt.data..'landmarks/' dirs = paths.dir(base_dir) lines = {} for i=1,#dirs do if string.sub(dirs[i],1,1) ~= '.' then for f in paths.files(base_dir..dirs[i],'.mat') do if not string.find(f, "test") then lines[#lines+1] = f end end end end print('=> Dataset built. '..#lines..' images were found.') return lines end function DataLoader.create(opt,split) local _dataset = nil local dataAnnot = DataLoader.getDataFaces(opt,split) return M.DataLoader(_dataset,opt,split,dataAnnot) end function DataLoader:__init(_dataset, opt, split, dataAnnot) local manualSeed = opt.manualSeed local function init() local datasets = require 'dataset-init' trainLoader, valLoader = datasets.create(opt,split,dataAnnot) end local function main(idx) if manualSeed ~= 0 then torch.manualSeed(manualSeed + idx) end torch.setnumthreads(1) _G.dataset = trainLoader return trainLoader:size() end local threads, sizes = Threads(opt.nThreads,init, main) self.nCrops = 1 self.threads = threads self.__size = sizes[1][1] self.batchSize = math.floor(opt.batchSize / self.nCrops) self.opt = opt self.split = split self.dataAnnot = dataAnnot end function DataLoader:size() return math.ceil(self.__size/self.batchSize) end function DataLoader:annot() trainLoader = datasets.create(self.opt,self.split,self.dataAnnot) return trainLoader.annot end function DataLoader:run() local threads = self.threads local size, batchSize = self.__size, self.batchSize local perm = torch.randperm(size) local idx, sample = 1, nil local function enqueue() while idx <= size and threads:acceptsjob() do local indices = perm:narrow(1,idx,math.min(batchSize,size-idx+1)) threads:addjob( function(indices,nCrops) local sz = indices:size(1) local batch, imageSize local target local indicesCopy = indices for i,idx in ipairs(indices:totable()) do local sample, label = _G.dataset:get(false,idx) local input, label = _G.dataset:preprocess(sample, label) if not batch then imageSize = input:size():totable() if nCrops > 1 then table.remove(imageSize,1) end batch = torch.FloatTensor(sz,nCrops, table.unpack(imageSize)) end if not target then targetSize = label:size():totable() target = torch.FloatTensor(sz,nCrops, table.unpack(targetSize)) end batch[i]:copy(input) target[i]:copy(label) end collectgarbage() return { input = batch:view(sz*nCrops,table.unpack(imageSize)), label = target:view(sz*nCrops,table.unpack(targetSize)), indx = indicesCopy , } end, function(_sample_) sample = _sample_ end, indices, self.nCrops ) idx = idx + batchSize end end local n = 0 local function loop() enqueue() if not threads:hasjob() then return nil end threads:dojob() if threads:haserror() then threads:synchronize() end enqueue() n = n+1 return n, sample end return loop end return M.DataLoader
local utils = require "kong.tools.utils" local singletons = require "kong.singletons" local conf_loader = require "kong.conf_loader" local cjson = require "cjson" local api_helpers = require "kong.api.api_helpers" local Schema = require "kong.db.schema" local Errors = require "kong.db.errors" local sub = string.sub local kong = kong local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local errors = Errors.new() local tagline = "Welcome to " .. _KONG._NAME local version = _KONG._VERSION local lua_version = jit and jit.version or _VERSION local strip_foreign_schemas = function(fields) for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] if fdata["type"] == "foreign" then fdata.schema = nil end end end return { ["/"] = { GET = function(self, dao, helpers) local distinct_plugins = setmetatable({}, cjson.array_mt) local prng_seeds = {} do local set = {} for row, err in kong.db.plugins:each() do if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error happened" }) end if not set[row.name] then distinct_plugins[#distinct_plugins+1] = row.name set[row.name] = true end end end do local kong_shm = ngx.shared.kong local shm_prefix = "pid: " local keys, err = kong_shm:get_keys() if not keys then ngx.log(ngx.ERR, "could not get kong shm keys: ", err) else for i = 1, #keys do if sub(keys[i], 1, #shm_prefix) == shm_prefix then prng_seeds[keys[i]], err = kong_shm:get(keys[i]) if err then ngx.log(ngx.ERR, "could not get PRNG seed from kong shm") end end end end end local node_id, err = knode.get_id() if node_id == nil then ngx.log(ngx.ERR, "could not get node id: ", err) end return kong.response.exit(200, { tagline = tagline, version = version, hostname = utils.get_hostname(), node_id = node_id, timers = { running = ngx.timer.running_count(), pending = ngx.timer.pending_count() }, plugins = { available_on_server = singletons.configuration.loaded_plugins, enabled_in_cluster = distinct_plugins }, lua_version = lua_version, configuration = conf_loader.remove_sensitive(singletons.configuration), prng_seeds = prng_seeds, }) end }, ["/schemas/:name"] = { GET = function(self, db, helpers) local entity = kong.db[self.params.name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(schema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, ["/schemas/:db_entity_name/validate"] = { POST = function(self, db, helpers) local db_entity_name = self.params.db_entity_name -- What happens when db_entity_name is a field name in the schema? self.params.db_entity_name = nil local entity = kong.db[db_entity_name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. db_entity_name .. "'" }) end local schema = assert(Schema.new(schema)) local _, err_t = schema:validate(schema:process_auto_fields( self.params, "insert")) if err_t then return kong.response.exit(400, errors:schema_violation(err_t)) end return kong.response.exit(200, { message = "schema validation successful" }) end }, ["/schemas/plugins/:name"] = { GET = function(self, db, helpers) local subschema = kong.db.plugins.schema.subschemas[self.params.name] if not subschema then return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(subschema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, }
----------------------------------- -- Area: Temple of Uggalepih -- NPC: ??? (Crimson-toothed Pawberry NM) -- !pos -39 -24 27 159 ----------------------------------- local ID = require("scripts/zones/Temple_of_Uggalepih/IDs") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player, npc, trade) if npcUtil.tradeHas(trade, 1183) and npcUtil.popFromQM(player, npc, {ID.mob.CRIMSON_TOOTHED_PAWBERRY, ID.mob.CRIMSON_TOOTHED_PAWBERRY + 2}, {hide = 900}) then player:confirmTrade() else player:messageSpecial(ID.text.NOTHING_HAPPENS) end end function onTrigger(player, npc) player:messageSpecial(ID.text.NM_OFFSET + 1) end
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local string = require('string') test('fs.readFile sync', function() local fn = Path.join(module.dir, 'fixtures', 'elipses.txt') local s = FS.readFileSync(fn) assert(s == string.rep(string.char(0xe2,0x80,0xA6), 10000)) assert(#s == 10000 * 3) end) end)
--[[ Description: ClientSide command handler. Author: Sceleratis Date: 12/25/2021 --]] local Root, Utilities, Service, Package; local RemoteCommands = {} local Commands = { DeclaredCommands = { } } --// Output local Verbose = false local function DebugWarn(...) if Verbose and Root and Root.Warn then Root.Warn(...) end end --- Responsible for client-side command handling. --- @class Client.Commands --- @client --- @tag Package: System.Admin --//// Remote commands --- Launches the client-side portion of commands. --- @function RunClientSideCommand --- @within Client.Remote.Commands --- @param cmdIndex string -- Command index --- @param ... any -- Command function parameters --- @return result function RemoteCommands.RunClientSideCommand(cmdIndex: string, ...) DebugWarn("DO CLIENT SIDE COMMAND", cmdIndex, ...) local foundCommand = Root.Commands.DeclaredCommands[cmdIndex] if foundCommand and foundCommand.ClientSide then DebugWarn("FOUND CLIENT SIDE COMMAND, RUNNING", foundCommand) return foundCommand.ClientSide(...) end end --- Declares settings to the client and updates command declaration setting proxies to correct values. --- @function FinishCommandDeclarations --- @within Client.Remote.Commands --- @param settings table -- Table containing settings sent by the server. function RemoteCommands.FinishCommandDeclarations(settings) DebugWarn("FINISH DECLARATION", settings) if settings then Utilities:MergeTables(Root.Settings, settings) end for ind,data in pairs(Root.Commands.DeclaredCommands) do Root.Commands:UpdateSettingProxies(data) end end --//// Commands methods --- Used by commands as a stand-in during definition for settings such as the command prefix. Navigates to a specified path, starting from Root. --- @interface SettingProxy --- @within Client.Commands --- @field __ROOT_PROXY boolean -- Identifies that this is a proxy object. --- @field Path string -- Path string (eg: "Settings" will resolve to Root.Settings) --- @field Index string -- When the destination table is reached, as indicated by path, said table will be indexed using Index as its key. --- Updates command settings proxies to their associated values in Root.Settings --- @method UpdateSettingsProxies --- @within Client.Commands --- @param data table -- SettingProxy function Commands.UpdateSettingProxies(self, data) DebugWarn("UPDATING COMMAND SETTING PROXIES", data) for i,v in pairs(data) do if type(v) == "table" and v.__ROOT_PROXY then local dest = Utilities:GetTableValueByPath(Root, v.Path) local setting = dest and dest.Value and dest.Value[v.Index] if setting then data[i] = setting else Root.Warn("Cannot update setting definition: Setting not found :: ", v.Index) end elseif type(v) == "table" then self:UpdateSettingProxies(v) end end end --- Declares a command or overwrites an existing declaration for the same CommandIndex. --- @method DeclareCommand --- @within Client.Commands --- @param CommandIndex string -- Command index. --- @param data {} -- Command data table function Commands.DeclareCommand(self, CommandIndex: string, data: {}) if self.DeclaredCommands[CommandIndex] then Root.Warn("CommandIndex \"".. CommandIndex .."\" already delcared. Overwriting.") end self.DeclaredCommands[CommandIndex] = data Utilities.Events.CommandDeclared:Fire(CommandIndex, data) DebugWarn("DECLARED NEW COMMAND", CommandIndex, data) end --//// Return initializer return { Init = function(cRoot, cPackage) Root = cRoot Package = cPackage Utilities = Root.Utilities Service = Root.Utilities.Services --// Do init Root.Commands = Commands Utilities:MergeTables(Root.Remote.Commands, RemoteCommands) end; AfterInit = function(Root, Package) --// Do after-init end; }
-- THREADS --------------------------------------------------------------------- -- Setup Citizen.CreateThread(function() -- Initialize ESX while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end -- Fetch player data Citizen.Wait(5000) PlayerData = ESX.GetPlayerData() end) -- Restrict vehicles Citizen.CreateThread(function() while true do Citizen.Wait(500) if Config.restricted then local thisPed = GetPlayerPed(PlayerId()) local thisVehicle = GetVehiclePedIsUsing(thisPed, false) local isEmergencyVehicle = ((GetVehicleClass(thisVehicle) == 18) or IsPedInAnyPoliceVehicle(thisPed)) local isDriver = (GetPedInVehicleSeat(thisVehicle, -1) == thisPed) local isAuthorized = false -- Check player job if PlayerData.job ~= nil then for _, v in ipairs(Config.allowed) do if v == PlayerData.job then isAuthorized = true break end end end -- Check player authorized if isEmergencyVehicle and isDriver and not isAuthorized then ESX.ShowNotification(_U('restricted')) SetVehicleUndriveable(thisVehicle, true) end end end end) -- EVENTS ---------------------------------------------------------------------- -- Initialize player data RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) PlayerData = xPlayer end) -- Initialize player jop RegisterNetEvent('esx:setJob') AddEventHandler('esx:setJob', function(job) PlayerData.job = job end)
local M = {} function M.check_health() local configs = require 'nvim_lsp/configs' for _, top_level_config in pairs(configs) do -- the folder needs to exist local new_config = top_level_config.make_config(".") local cmd, _ = vim.lsp._cmd_parts(new_config.cmd) if not (vim.fn.executable(cmd) == 1) then vim.fn['health#report_error']( string.format("%s: The given command %q is not executable.", new_config.name, cmd) ) else vim.fn['health#report_info']( string.format("%s: configuration checked.", new_config.name) ) end end end return M
local utf8 = require "ng.utf8" local s = "привет" assert(utf8.RuneCount(s) == 6) local rune, size rune, size = utf8.DecodeRune(s) assert(rune == 1087) assert(size == 2) rune, size = utf8.DecodeLastRune(s) assert(rune == 1090) assert(size == 2) rune, size = utf8.DecodeRune(s, 3) assert(rune == 1088) assert(size == 2) rune, size = utf8.DecodeLastRune(s, #s - 2) assert(rune == 1077) assert(size == 2)
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.history") -- the macro directories function _directories() return { path.join(config.directory(), "macros") , path.join(os.scriptdir(), "macros")} end -- the macro directory function _directory(macroname) -- find macro directory local macrodir = nil for _, dir in ipairs(_directories()) do -- found? if os.isfile(path.join(dir, macroname .. ".lua")) then macrodir = dir break end end -- check assert(macrodir, "macro(%s) not found!", macroname) -- ok return macrodir end -- the readable macro file function _rfile(macroname) -- is anonymous? if macroname == '.' then macroname = "anonymous" end -- get it return path.join(_directory(macroname), macroname .. ".lua") end -- the writable macro file function _wfile(macroname) -- is anonymous? if macroname == '.' then macroname = "anonymous" end -- get it return path.join(path.join(config.directory(), "macros"), macroname .. ".lua") end -- list macros function _list() -- trace cprint("${bright}macros:") -- find all macros for _, dir in ipairs(_directories()) do local macrofiles = os.match(path.join(dir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- get macro name local macroname = path.basename(macrofile) if macroname == "anonymous" then macroname = ".<anonymous>" end -- show it print(" " .. macroname) end end end -- show macro function _show(macroname) -- show it local file = _rfile(macroname) if os.isfile(file) then io.cat(file) else raise("macro(%s) not found!", macroname) end end -- clear all macros function _clear() -- clear all os.rm(path.join(config.directory(), "macros")) end -- delete macro function _delete(macroname) -- remove it if os.isfile(_wfile(macroname)) then os.rm(_wfile(macroname)) elseif os.isfile(_rfile(macroname)) then raise("macro(%s) cannot be deleted!", macroname) else raise("macro(%s) not found!", macroname) end -- trace cprint("${bright}delete macro(%s) ok!", macroname) end -- import macro function _import(macrofile, macroname) -- import all macros if os.isdir(macrofile) then -- the macro directory local macrodir = macrofile local macrofiles = os.match(path.join(macrodir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- the macro name macroname = path.basename(macrofile) -- import it os.cp(macrofile, _wfile(macroname)) -- trace cprint("${bright}import macro(%s) ok!", macroname) end else -- import it os.cp(macrofile, _wfile(macroname)) -- trace cprint("${bright}import macro(%s) ok!", macroname) end end -- export macro function _export(macrofile, macroname) -- export all macros if os.isdir(macrofile) then -- the output directory local outputdir = macrofile -- export all macros for _, dir in ipairs(_directories()) do local macrofiles = os.match(path.join(dir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- export it os.cp(macrofile, outputdir) -- trace cprint("${bright}export macro(%s) ok!", path.basename(macrofile)) end end else -- export it os.cp(_rfile(macroname), macrofile) -- trace cprint("${bright}export macro(%s) ok!", macroname) end end -- begin to record macro function _begin() -- patch begin tag to the history: cmdlines history("local.history"):save("cmdlines", "__macro_begin__") end -- end to record macro function _end(macroname) -- load the history: cmdlines local cmdlines = history("local.history"):load("cmdlines") -- get the last macro block local begin = false local block = {} if cmdlines then local total = #cmdlines local index = total while index ~= 0 do -- the command line local cmdline = cmdlines[index] -- found begin? break it if cmdline == "__macro_begin__" then begin = true break end -- found end? break it if cmdline == "__macro_end__" then break end -- ignore "xmake m .." and "xmake macro .." if not cmdline:find("xmake%s+macro%s*") and not cmdline:find("xmake%s+m%s*") then -- save this command line to block table.insert(block, 1, cmdline) end -- the previous line index = index - 1 end end -- the begin tag not found? if not begin then raise("please run: 'xmake macro --begin' first!") end -- patch end tag to the history: cmdlines history("local.history"):save("cmdlines", "__macro_end__") -- open the macro file local file = io.open(_wfile(macroname), "w") -- save the macro begin file:print("function main(argv)") -- save the macro block for _, cmdline in ipairs(block) do -- save command line file:print(" os.exec(\"%s\")", (cmdline:gsub("[\\\"]", function (w) return "\\" .. w end))) end -- save the macro end file:print("end") -- exit the macro file file:close() -- show this macro _show(macroname) -- trace cprint("${bright}define macro(%s) ok!", macroname) end -- run macro function _run(macroname) -- run last command? if macroname == ".." then -- load the history: cmdlines local cmdlines = history("local.history"):load("cmdlines") -- get the last command local lastcmd = nil if cmdlines then local total = #cmdlines local index = total while index ~= 0 do -- ignore "xmake m .." and "xmake macro .." local cmdline = cmdlines[index] if not cmdline:startswith("__macro_") and not cmdline:find("xmake%s+macro%s*") and not cmdline:find("xmake%s+m%s*") then lastcmd = cmdline break end -- the previous line index = index - 1 end end -- run the last command if lastcmd then os.exec(lastcmd) end return end -- is anonymous? if macroname == '.' then macroname = "anonymous" end -- run macro import(macroname, {rootdir = _directory(macroname), anonymous = true})(option.get("arguments") or {}) end -- main function main() -- list macros if option.get("list") then _list() -- show macro elseif option.get("show") then _show(option.get("name")) -- clear macro elseif option.get("clear") then _clear() -- delete macro elseif option.get("delete") then _delete(option.get("name")) -- import macro elseif option.get("import") then _import(option.get("import"), option.get("name")) -- export macro elseif option.get("export") then _export(option.get("export"), option.get("name")) -- begin to record macro elseif option.get("begin") then _begin() -- end to record macro elseif option.get("end") then _end(option.get("name")) -- run macro else _run(option.get("name")) end end
function SetChallengePointsTag(uuid) local cp = GetVarInteger(uuid, "LLENEMY_ChallengePoints") if cp == nil or cp < 0 then cp = 0 end LeaderLib.PrintDebug("[EUO:UpgradeInfo.lua:SetChallengePointsTag] Character ("..uuid..") CP("..tostring(cp)..")") for k,tbl in pairs(ChallengePointsText) do if cp >= tbl.Min and cp <= tbl.Max then SetTag(uuid, tbl.Tag) UpgradeInfo_ApplyInfoStatus(uuid,true) else ClearTag(uuid, tbl.Tag) end end end local function HasUpgrades(uuid) for key,group in pairs(UpgradeData) do for status,infoText in pairs(group) do if HasActiveStatus(uuid, status) == 1 then return true end end end return false end function UpgradeInfo_ApplyInfoStatus(uuid,force) local hasUpgrades = HasUpgrades(uuid) if hasUpgrades or force == true then ApplyStatus(uuid, "LLENEMY_UPGRADE_INFO", -1.0, 1, uuid) elseif hasUpgrades == false then RemoveStatus(uuid, "LLENEMY_UPGRADE_INFO") end end function UpgradeInfo_RefreshInfoStatuses() local combatCharacters = Osi.DB_CombatCharacters:Get(nil,nil) if #combatCharacters > 0 then for i,entry in pairs(combatCharacters) do local uuid = entry[1] if HasActiveStatus(uuid, "LLENEMY_UPGRADE_INFO") == 1 then --local handle = NRD_StatusGetHandle(uuid, "LLENEMY_UPGRADE_INFO") --NRD_StatusSetReal(uuid, handle, "LifeTime", 24.0) --NRD_StatusSetReal(uuid, handle, "CurrentLifeTime", 24.0) --NRD_StatusSetReal(uuid, handle, "LifeTime", -1.0) --NRD_StatusSetReal(uuid, handle, "CurrentLifeTime", -1.0) ApplyStatus(uuid, "LLENEMY_UPGRADE_INFO", -1.0, 1, uuid) end end LeaderLib.PrintDebug("[EUO:UpgradeInfo.lua:RefreshInfoStatuses] Refreshed upgrade info on characters in combat.") end end local function GetHighestPartyLoremaster() local nextHighest = 0 local players = Osi.DB_IsPlayer:Get(nil) for _,entry in pairs(players) do local uuid = entry[1] local character = Ext.GetCharacter(uuid) if character ~= nil then if character.Stats.Loremaster > nextHighest then nextHighest = character.Stats.Loremaster end end end return nextHighest end function SetHighestPartyLoremaster() HighestLoremaster = GetHighestPartyLoremaster() if Ext.GetGameState() == "Running" then Ext.BroadcastMessage("LLENEMY_SetHighestLoremaster", tostring(HighestLoremaster), nil) LeaderLib.PrintDebug("[EUO:SetHighestPartyLoremaster] Synced highest party loremaster.",HighestLoremaster) else TimerCancel("Timers_LLENEMY_SyncHighestLoremaster") TimerLaunch("Timers_LLENEMY_SyncHighestLoremaster", 500) end end -- Loremaster local function SaveHighestLoremaster(player, stat, lastVal, nextVal) local nextHighest = HighestLoremaster if player ~= nil then if nextVal >= nextHighest then local lore = CharacterGetAbility(player, "Loremaster") if lore >= HighestLoremaster then nextHighest = lore end elseif nextVal < lastVal then nextHighest = GetHighestPartyLoremaster() end else nextHighest = GetHighestPartyLoremaster() end if HighestLoremaster ~= nextHighest then HighestLoremaster = nextHighest if Ext.GetGameState() == "Running" then Ext.BroadcastMessage("LLENEMY_SetHighestLoremaster", tostring(HighestLoremaster), nil) else TimerCancel("Timers_LLENEMY_SyncHighestLoremaster") TimerLaunch("Timers_LLENEMY_SyncHighestLoremaster", 500) end end end local function CharacterBasePointsChanged(player, stat, lastVal, nextVal) if stat == "Loremaster" then SaveHighestLoremaster(player, stat, lastVal, nextVal) end end LeaderLib.RegisterListener("CharacterBasePointsChanged", CharacterBasePointsChanged) -- event CharacterBaseAbilityChanged((CHARACTERGUID)_Character, (STRING)_Ability, (INTEGER)_OldBaseValue, (INTEGER)_NewBaseValue) ---@type character string ---@type ability string ---@type old integer ---@type new integer local function OnCharacterBaseAbilityChanged(character, ability, old, new) if ability == "Loremaster" and CharacterIsPlayer(character) == 1 and CharacterIsSummon(character) == 0 and CharacterIsPartyFollower(character) == 0 then SaveHighestLoremaster(character, ability, old, new) end end Ext.RegisterOsirisListener("CharacterBaseAbilityChanged", 4, "after", OnCharacterBaseAbilityChanged) Ext.RegisterOsirisListener("UserConnected", 3, "after", function(id, username, profileId) HighestLoremaster = GetHighestPartyLoremaster() if Ext.GetGameState() == "Running" and GetCurrentCharacter(id) ~= nil then Ext.PostMessageToUser(id, "LLENEMY_SetHighestLoremaster", tostring(HighestLoremaster)) else TimerCancel("Timers_LLENEMY_SyncHighestLoremaster") TimerLaunch("Timers_LLENEMY_SyncHighestLoremaster", 500) end end)
----------------------------------- -- -- Zone: Southern_San_dOria_[S] (80) -- ----------------------------------- local ID = require("scripts/zones/Southern_San_dOria_[S]/IDs"); require("scripts/globals/missions"); require("scripts/globals/settings"); require("scripts/globals/chocobo") require("scripts/globals/quests"); require("scripts/globals/zone") ----------------------------------- function onInitialize(zone) tpz.chocobo.initZone(zone) end; function onZoneIn(player,prevZone) local cs = -1; if (prevZone == tpz.zone.EAST_RONFAURE_S) then if (player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.KNOT_QUITE_THERE) == QUEST_ACCEPTED and player:getCharVar("KnotQuiteThere") == 2) then cs = 62; elseif (player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.DOWNWARD_HELIX) == QUEST_ACCEPTED and player:getCharVar("DownwardHelix") == 0) then cs = 65; elseif (player:getCurrentMission(WOTG) == tpz.mission.id.wotg.CAIT_SITH and (player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.WRATH_OF_THE_GRIFFON) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.A_MANIFEST_PROBLEM) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.BURDEN_OF_SUSPICION) == QUEST_COMPLETED)) then cs = 67; end end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(161,-2,161,94); if (player:getMainJob() ~= player:getCharVar("PlayerMainJob")) then cs = 30004; end player:setCharVar("PlayerMainJob",0); end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 62) then player:setCharVar("KnotQuiteThere",3); elseif (csid == 65) then player:setCharVar("DownwardHelix",1); elseif (csid == 67) then player:completeMission(WOTG, tpz.mission.id.wotg.CAIT_SITH); player:addMission(WOTG, tpz.mission.id.wotg.THE_QUEEN_OF_THE_DANCE); end end;
--- Syntax sugar. -- return { --- Sweeten a function. This effectively allows functions taking multiple -- arguments to be "called without parentheses." You probably don't need -- to use this. -- -- @param fn A function taking a fixed number of non-optional arguments. -- -- @param argc The number of arguments `fn` takes. If `fn` is a table -- method, `argc` should include the hidden `self` argument. -- -- @return A wrapper function for `fn`. -- If the wrapper is called with less than `argc` arguments, it will -- return a *continuation object* that can be called or concatenated -- with any remaining arguments. Otherwise, it will tail-call `fn` -- and return the result. -- sweeten = function(fn, argc) local wrapper argc = tonumber(argc) or 2 local function unpack_plus(t, i, ...) i = i or 1 if i <= #t then return t[i], unpack_plus(t, i + 1, ...) else return ... end end local function resume(t, ...) return wrapper(unpack_plus(t, 1, ...)) end local meta = { __call = resume, __concat = resume } wrapper = function(...) if select('#', ...) >= argc then return fn(...) else return setmetatable({...}, meta) end end return wrapper end, }
local skynet = require "skynet" skynet.start(function() print("Main Server start") local console = skynet.newservice( "testmongodb", "127.0.0.1", 27017, "testdb", "test", "test" ) print("Main Server exit") skynet.exit() end)
if not modules then modules = { } end modules ['back-exp'] = { version = 1.001, comment = "companion to back-exp.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- Todo: share properties more with tagged pdf (or thge reverse) -- Because we run into the 200 local limit we quite some do .. end wrappers .. not always -- that nice but it has to be. -- Experiments demonstrated that mapping to <div> and classes is messy because we have to -- package attributes (some 30) into one set of (space seperatated but prefixed classes) -- which only makes things worse .. so if you want something else, use xslt to get there. -- language -> only mainlanguage, local languages should happen through start/stoplanguage -- tocs/registers -> maybe add a stripper (i.e. just don't flush entries in final tree) -- footnotes -> css 3 -- bodyfont -> in styles.css -- Because we need to look ahead we now always build a tree (this was optional in -- the beginning). The extra overhead in the frontend is neglectable. -- -- We can optimize the code ... currently the overhead is some 10% for xml + html so -- there is no hurry. -- todo: move critital formatters out of functions -- todo: delay loading (apart from basic tag stuff) -- problem : too many local variables -- check setting __i__ local next, type, tonumber = next, type, tonumber local sub, gsub = string.sub, string.gsub local validstring = string.valid local lpegmatch = lpeg.match local utfchar, utfvalues = utf.char, utf.values local concat, insert, remove, merge = table.concat, table.insert, table.remove, table.merge local sortedhash = table.sortedhash local formatters = string.formatters local todimen = number.todimen local replacetemplate = utilities.templates.replace local trace_export = false trackers.register ("export.trace", function(v) trace_export = v end) local trace_spacing = false trackers.register ("export.trace.spacing", function(v) trace_spacing = v end) local less_state = false directives.register("export.lessstate", function(v) less_state = v end) local show_comment = true directives.register("export.comment", function(v) show_comment = v end) show_comment = false -- figure out why break comment -- maybe we will also support these: -- -- local css_hyphens = false directives.register("export.css.hyphens", function(v) css_hyphens = v end) -- local css_textalign = false directives.register("export.css.textalign", function(v) css_textalign = v end) -- local css_bodyfontsize = false directives.register("export.css.bodyfontsize", function(v) css_bodyfontsize = v end) -- local css_textwidth = false directives.register("export.css.textwidth", function(v) css_textwidth = v end) local report_export = logs.reporter("backend","export") local nodes = nodes local attributes = attributes local variables = interfaces.variables local v_yes = variables.yes local v_no = variables.no local v_hidden = variables.hidden local implement = interfaces.implement local settings_to_array = utilities.parsers.settings_to_array local setmetatableindex = table.setmetatableindex local tasks = nodes.tasks local fontchar = fonts.hashes.characters local fontquads = fonts.hashes.quads local languagenames = languages.numbers local nodecodes = nodes.nodecodes local skipcodes = nodes.skipcodes local listcodes = nodes.listcodes local hlist_code = nodecodes.hlist local vlist_code = nodecodes.vlist local glyph_code = nodecodes.glyph local glue_code = nodecodes.glue local kern_code = nodecodes.kern local disc_code = nodecodes.disc local userskip_code = skipcodes.userskip local rightskip_code = skipcodes.rightskip local parfillskip_code = skipcodes.parfillskip local spaceskip_code = skipcodes.spaceskip local xspaceskip_code = skipcodes.xspaceskip local line_code = listcodes.line local texgetcount = tex.getcount local privateattribute = attributes.private local a_characters = privateattribute('characters') local a_exportstatus = privateattribute('exportstatus') local a_tagged = privateattribute('tagged') local a_taggedpar = privateattribute("taggedpar") local a_image = privateattribute('image') local a_reference = privateattribute('reference') local a_textblock = privateattribute("textblock") local nuts = nodes.nuts local tonut = nuts.tonut local getnext = nuts.getnext local getsubtype = nuts.getsubtype local getfont = nuts.getfont local getdisc = nuts.getdisc local getlist = nuts.getlist local getid = nuts.getid local getfield = nuts.getfield local getattr = nuts.getattr local setattr = nuts.setattr local isglyph = nuts.isglyph local traverse_id = nuts.traverse_id local traverse_nodes = nuts.traverse local references = structures.references local structurestags = structures.tags local taglist = structurestags.taglist local specifications = structurestags.specifications local properties = structurestags.properties local locatedtag = structurestags.locatedtag structurestags.usewithcare = { } local starttiming = statistics.starttiming local stoptiming = statistics.stoptiming local characterdata = characters.data local overloads = fonts.mappings.overloads -- todo: more locals (and optimize) local exportversion = "0.34" local mathmlns = "http://www.w3.org/1998/Math/MathML" local contextns = "http://www.contextgarden.net/context/export" -- whatever suits local cssnamespaceurl = "@namespace context url('%namespace%') ;" local cssnamespace = "context|" ----- cssnamespacenop = "/* no namespace */" local usecssnamespace = false local nofcurrentcontent = 0 -- so we don't free (less garbage collection) local currentcontent = { } local currentnesting = nil local currentattribute = nil local last = nil local currentparagraph = nil local noftextblocks = 0 local hyphencode = 0xAD local hyphen = utfchar(0xAD) -- todo: also emdash etc local tagsplitter = structurestags.patterns.splitter ----- colonsplitter = lpeg.splitat(":") ----- dashsplitter = lpeg.splitat("-") local threshold = 65536 local indexing = false local keephyphens = false local exportproperties = false local finetuning = { } local treestack = { } local nesting = { } local currentdepth = 0 local wrapups = { } local tree = { data = { }, fulltag == "root" } -- root local treeroot = tree local treehash = { } local extras = { } local checks = { } local finalizers = { } local nofbreaks = 0 local used = { } local exporting = false local restart = false local specialspaces = { [0x20] = " " } -- for conversion local somespace = { [0x20] = true, [" "] = true } -- for testing local entities = { ["&"] = "&amp;", [">"] = "&gt;", ["<"] = "&lt;" } local attribentities = { ["&"] = "&amp;", [">"] = "&gt;", ["<"] = "&lt;", ['"'] = "quot;" } local p_entity = lpeg.replacer(entities) -- was: entityremapper = utf.remapper(entities) local p_attribute = lpeg.replacer(attribentities) local p_stripper = lpeg.patterns.stripper local p_escaped = lpeg.patterns.xml.escaped local f_tagid = formatters["%s-%04i"] -- local alignmapping = { -- flushright = "right", -- middle = "center", -- flushleft = "left", -- } local defaultnature = "mixed" -- "inline" setmetatableindex(used, function(t,k) if k then local v = { } t[k] = v return v end end) local f_entity = formatters["&#x%X;"] local f_attribute = formatters[" %s=%q"] local f_property = formatters[" %s%s=%q"] setmetatableindex(specialspaces, function(t,k) local v = utfchar(k) t[k] = v entities[v] = f_entity(k) somespace[k] = true somespace[v] = true return v end) local namespaced = { -- filled on } local namespaces = { msubsup = "m", msub = "m", msup = "m", mn = "m", mi = "m", ms = "m", mo = "m", mtext = "m", mrow = "m", mfrac = "m", mroot = "m", msqrt = "m", munderover = "m", munder = "m", mover = "m", merror = "m", math = "m", mrow = "m", mtable = "m", mtr = "m", mtd = "m", mfenced = "m", maction = "m", mspace = "m", -- only when testing mstacker = "m", mstackertop = "m", mstackermid = "m", mstackerbot = "m", } setmetatableindex(namespaced, function(t,k) if k then local namespace = namespaces[k] local v = namespace and namespace .. ":" .. k or k t[k] = v return v end end) local function attribute(key,value) if value and value ~= "" then return f_attribute(key,lpegmatch(p_attribute,value)) else return "" end end local function setattribute(di,key,value,escaped) if value and value ~= "" then local a = di.attributes if escaped then value = lpegmatch(p_escaped,value) end if not a then di.attributes = { [key] = value } else a[key] = value end end end local listdata = { } -- this has to be done otherwise: each element can just point back to ... function wrapups.hashlistdata() local c = structures.lists.collected for i=1,#c do local ci = c[i] local tag = ci.references.tag if tag then local m = ci.metadata local t = m.kind .. ">" .. tag -- todo: use internal (see strc-lst.lua where it's set) listdata[t] = ci end end end function structurestags.setattributehash(attr,key,value) -- public hash local specification = taglist[attr] if specification then specification[key] = value else -- some kind of error end end local usedstyles = { } local namespacetemplate = [[ /* %what% for file %filename% */ %cssnamespaceurl% ]] do -- experiment: styles and images -- -- officially we should convert to bp but we round anyway -- /* padding : ; */ -- /* text-justify : inter-word ; */ -- /* text-align : justify ; */ local documenttemplate = [[ document, %namespace%div.document { font-size : %size% !important ; max-width : %width% !important ; text-width : %align% !important ; hyphens : %hyphens% !important ; } ]] local styletemplate = [[ %element%[detail="%detail%"], %namespace%div.%element%.%detail% { display : inline ; font-style : %style% ; font-variant : %variant% ; font-weight : %weight% ; font-family : %family% ; color : %color% ; }]] local numbertoallign = { [0] = "justify", ["0"] = "justify", [variables.normal ] = "justify", [1] = "right", ["1"] = "right", [variables.flushright] = "right", [2] = "center", ["2"] = "center", [variables.middle ] = "center", [3] = "left", ["3"] = "left", [variables.flushleft ] = "left", } function wrapups.allusedstyles(basename) local result = { replacetemplate(namespacetemplate, { what = "styles", filename = basename, namespace = contextns, -- cssnamespaceurl = usecssnamespace and cssnamespaceurl or cssnamespacenop, cssnamespaceurl = cssnamespaceurl, }) } -- local bodyfont = finetuning.bodyfont local width = finetuning.width local hyphen = finetuning.hyphen local align = finetuning.align -- if type(bodyfont) == "number" then bodyfont = todimen(bodyfont) else bodyfont = "12pt" end if type(width) == "number" then width = todimen(width) or "50em" else width = "50em" end if hyphen == v_yes then hyphen = "manual" else hyphen = "inherited" end if align then align = numbertoallign[align] end if not align then align = hyphen and "justify" or "inherited" end -- result[#result+1] = replacetemplate(documenttemplate,{ size = bodyfont, width = width, align = align, hyphens = hyphen }) -- local colorspecification = xml.css.colorspecification local fontspecification = xml.css.fontspecification for element, details in sortedhash(usedstyles) do for detail, data in sortedhash(details) do local s = fontspecification(data.style) local c = colorspecification(data.color) detail = gsub(detail,"[^A-Za-z0-9]+","-") result[#result+1] = replacetemplate(styletemplate,{ namespace = usecssnamespace and cssnamespace or "", element = element, detail = detail, style = s.style or "inherit", variant = s.variant or "inherit", weight = s.weight or "inherit", family = s.family or "inherit", color = c or "inherit", }) end end return concat(result,"\n\n") end end local usedimages = { } do local imagetemplate = [[ %element%[id="%id%"], %namespace%div.%element%[id="%id%"] { display : block ; background-image : url('%url%') ; background-size : 100%% auto ; background-repeat : no-repeat ; width : %width% ; height : %height% ; }]] local f_svgname = formatters["%s.svg"] local f_svgpage = formatters["%s-page-%s.svg"] local collected = { } local function usedname(name,page) if file.suffix(name) == "pdf" then -- temp hack .. we will have a remapper if page and page > 1 then name = f_svgpage(file.nameonly(name),page) else name = f_svgname(file.nameonly(name)) end end local scheme = url.hasscheme(name) if not scheme or scheme == "file" then -- or can we just use the name ? return file.join("../images",file.basename(url.filename(name))) else return name end end function wrapups.allusedimages(basename) local result = { replacetemplate(namespacetemplate, { what = "images", filename = basename, namespace = contextns, -- cssnamespaceurl = usecssnamespace and cssnamespaceurl or "", cssnamespaceurl = cssnamespaceurl, }) } for element, details in sortedhash(usedimages) do for detail, data in sortedhash(details) do local name = data.name local page = tonumber(data.page) or 1 local spec = { element = element, id = data.id, name = name, page = page, url = usedname(name,page), width = data.width, height = data.height, used = data.used, namespace = usecssnamespace and cssnamespace or "", } result[#result+1] = replacetemplate(imagetemplate,spec) collected[detail] = spec end end return concat(result,"\n\n") end function wrapups.uniqueusedimages() -- todo: combine these two return collected end end -- properties.vspace = { export = "break", nature = "display" } ----------------- = { export = "pagebreak", nature = "display" } local function makebreaklist(list) nofbreaks = nofbreaks + 1 local t = { } local l = list and list.taglist if l then for i=1,#list do t[i] = l[i] end end t[#t+1] = "break>" .. nofbreaks -- maybe no number or 0 return { taglist = t } end local breakattributes = { type = "collapse" } local function makebreaknode(attributes) -- maybe no fulltag nofbreaks = nofbreaks + 1 return { tg = "break", fulltag = "break>" .. nofbreaks, n = nofbreaks, element = "break", nature = "display", attributes = attributes or nil, -- data = { }, -- not needed -- attribute = 0, -- not needed -- parnumber = 0, } end local function ignorebreaks(di,element,n,fulltag) local data = di.data for i=1,#data do local d = data[i] if d.content == " " then d.content = "" end end end local function ignorespaces(di,element,n,fulltag) local data = di.data for i=1,#data do local d = data[i] local c = d.content if type(c) == "string" then d.content = lpegmatch(p_stripper,c) end end end do local fields = { "title", "subtitle", "author", "keywords" } local function checkdocument(root) local data = root.data if data then for i=1,#data do local di = data[i] local tg = di.tg if tg == "noexport" then local s = specifications[di.fulltag] local u = s and s.userdata if u then local comment = u.comment if comment then di.element = "comment" di.data = { { content = comment } } u.comment = nil else data[i] = false end else data[i] = false end elseif di.content then -- okay elseif tg == "ignore" then di.element = "" checkdocument(di) else checkdocument(di) -- new, else no noexport handling end end end end function extras.document(di,element,n,fulltag) setattribute(di,"language",languagenames[texgetcount("mainlanguagenumber")]) if not less_state then setattribute(di,"file",tex.jobname) setattribute(di,"date",os.date()) setattribute(di,"context",environment.version) setattribute(di,"version",exportversion) setattribute(di,"xmlns:m",mathmlns) local identity = interactions.general.getidentity() for i=1,#fields do local key = fields[i] local value = identity[key] if value and value ~= "" then setattribute(di,key,value) end end end checkdocument(di) end end do local symbols = { } function structurestags.settagdelimitedsymbol(symbol) symbols[locatedtag("delimitedsymbol")] = { symbol = symbol, } end function extras.delimitedsymbol(di,element,n,fulltag) local hash = symbols[fulltag] if hash then setattribute(di,"symbol",hash.symbol or nil) end end end do local symbols = { } function structurestags.settagsubsentencesymbol(symbol) symbols[locatedtag("subsentencesymbol")] = { symbol = symbol, } end function extras.subsentencesymbol(di,element,n,fulltag) local hash = symbols[fulltag] if hash then setattribute(di,"symbol",hash.symbol or nil) end end end do local itemgroups = { } function structurestags.setitemgroup(packed,level,symbol) itemgroups[locatedtag("itemgroup")] = { packed = packed, symbol = symbol, level = level, } end function structurestags.setitem(kind) itemgroups[locatedtag("item")] = { kind = kind, } end function extras.itemgroup(di,element,n,fulltag) local hash = itemgroups[fulltag] if hash then setattribute(di,"packed",hash.packed and "yes" or nil) setattribute(di,"symbol",hash.symbol) setattribute(di,"level",hash.level) end end function extras.item(di,element,n,fulltag) local hash = itemgroups[fulltag] if hash then local kind = hash.kind if kind and kind ~= "" then setattribute(di,"kind",kind) end end end end do local synonyms = { } local sortings = { } function structurestags.setsynonym(tag) synonyms[locatedtag("synonym")] = tag end function extras.synonym(di,element,n,fulltag) local tag = synonyms[fulltag] if tag then setattribute(di,"tag",tag) end end function structurestags.setsorting(tag) sortings[locatedtag("sorting")] = tag end function extras.sorting(di,element,n,fulltag) local tag = sortings[fulltag] if tag then setattribute(di,"tag",tag) end end end do local highlight = { } usedstyles.highlight = highlight local strippedtag = structurestags.strip -- we assume global styles function structurestags.sethighlight(style,color) highlight[strippedtag(locatedtag("highlight"))] = { style = style, -- xml.css.fontspecification(style), color = color, -- xml.css.colorspec(color), } end end do local descriptions = { } local symbols = { } local linked = { } -- we could move the notation itself to the first reference (can be an option) function structurestags.setnotation(tag,n) -- needs checking (is tag needed) -- we can also use the internals hash or list local nd = structures.notes.get(tag,n) if nd then local references = nd.references descriptions[references and references.internal] = locatedtag("description") end end function structurestags.setnotationsymbol(tag,n) -- needs checking (is tag needed) local nd = structures.notes.get(tag,n) -- todo: use listdata instead if nd then local references = nd.references symbols[references and references.internal] = locatedtag("descriptionsymbol") end end function finalizers.descriptions(tree) local n = 0 for id, tag in next, descriptions do local sym = symbols[id] if sym then n = n + 1 linked[tag] = n linked[sym] = n end end end function extras.description(di,element,n,fulltag) local id = linked[fulltag] if id then setattribute(di,"insert",id) end end function extras.descriptionsymbol(di,element,n,fulltag) local id = linked[fulltag] if id then setattribute(di,"insert",id) end end end -- -- todo: ignore breaks -- -- function extras.verbatimline(di,element,n,fulltag) -- inspect(di) -- end do local f_id = formatters["%s-%s"] local image = { } usedimages.image = image structurestags.usewithcare.images = image function structurestags.setfigure(name,used,page,width,height,label) local fulltag = locatedtag("image") local spec = specifications[fulltag] local page = tonumber(page) image[fulltag] = { id = f_id(spec.tagname,spec.tagindex), name = name, used = used, page = page and page > 1 and page or nil, width = todimen(width, "cm","%0.3F%s"), height = todimen(height,"cm","%0.3F%s"), label = label, } end function extras.image(di,element,n,fulltag) local data = image[fulltag] if data then setattribute(di,"name",data.name) setattribute(di,"page",data.page) setattribute(di,"id",data.id) setattribute(di,"width",data.width) setattribute(di,"height",data.height) setattribute(di,"label",data.height) end end end do local combinations = { } function structurestags.setcombination(nx,ny) combinations[locatedtag("combination")] = { nx = nx, ny = ny, } end function extras.combination(di,element,n,fulltag) local data = combinations[fulltag] if data then setattribute(di,"nx",data.nx) setattribute(di,"ny",data.ny) end end end -- quite some code deals with exporting references -- -- links: -- -- url : -- file : -- internal : automatic location -- location : named reference -- references: -- -- implicit : automatic reference -- explicit : named reference local evaluators = { } local specials = { } local explicits = { } evaluators.inner = function(di,var) local inner = var.inner if inner then setattribute(di,"location",inner,true) end end evaluators.outer = function(di,var) local file, url = references.checkedfileorurl(var.outer,var.outer) if url then setattribute(di,"url",url,true) elseif file then setattribute(di,"file",file,true) end end evaluators["outer with inner"] = function(di,var) local file = references.checkedfile(var.f) if file then setattribute(di,"file",file,true) end local inner = var.inner if inner then setattribute(di,"inner",inner,true) end end evaluators.special = function(di,var) local handler = specials[var.special] if handler then handler(di,var) end end local referencehash = { } do evaluators["special outer with operation"] = evaluators.special evaluators["special operation"] = evaluators.special evaluators["special operation with arguments"] = evaluators.special function specials.url(di,var) local url = references.checkedurl(var.operation) if url and url ~= "" then setattribute(di,"url",url,true) end end function specials.file(di,var) local file = references.checkedfile(var.operation) if file and file ~= "" then setattribute(di,"file",file,true) end end function specials.fileorurl(di,var) local file, url = references.checkedfileorurl(var.operation,var.operation) if url and url ~= "" then setattribute(di,"url",url,true) elseif file and file ~= "" then setattribute(di,"file",file,true) end end function specials.internal(di,var) local internal = references.checkedurl(var.operation) if internal then setattribute(di,"location",internal) end end local function adddestination(di,references) -- todo: specials -> exporters and then concat if references then local reference = references.reference if reference and reference ~= "" then local prefix = references.prefix if prefix and prefix ~= "" then setattribute(di,"prefix",prefix,true) end setattribute(di,"destination",reference,true) for i=1,#references do local r = references[i] local e = evaluators[r.kind] if e then e(di,r) end end end end end function extras.addimplicit(di,references) if references then local internal = references.internal if internal then setattribute(di,"implicit",internal) end end end function extras.addinternal(di,references) if references then local internal = references.internal if internal then setattribute(di,"internal",internal) end end end local p_firstpart = lpeg.Cs((1-lpeg.P(","))^0) local function addreference(di,references) if references then local reference = references.reference if reference and reference ~= "" then local prefix = references.prefix if prefix and prefix ~= "" then setattribute(di,"prefix",prefix) end setattribute(di,"reference",reference,true) setattribute(di,"explicit",lpegmatch(p_firstpart,reference),true) end local internal = references.internal if internal and internal ~= "" then setattribute(di,"implicit",internal) end end end local function link(di,element,n,fulltag) -- for instance in lists a link has nested elements and no own text local reference = referencehash[fulltag] if reference then adddestination(di,structures.references.get(reference)) return true else local data = di.data if data then for i=1,#data do local di = data[i] if di then local fulltag = di.fulltag if fulltag and link(di,element,n,fulltag) then return true end end end end end end extras.adddestination = adddestination extras.addreference = addreference extras.link = link end -- no settings, as these are obscure ones do local automathrows = true directives.register("export.math.autorows", function(v) automathrows = v end) local automathapply = true directives.register("export.math.autoapply", function(v) automathapply = v end) local automathnumber = true directives.register("export.math.autonumber", function(v) automathnumber = v end) local automathstrip = true directives.register("export.math.autostrip", function(v) automathstrip = v end) local functions = mathematics.categories.functions local function collapse(di,i,data,ndata,detail,element) local collapsing = di.data if data then di.element = element di.detail = nil i = i + 1 while i <= ndata do local dn = data[i] if dn.detail == detail then collapsing[#collapsing+1] = dn.data[1] dn.skip = "ignore" i = i + 1 else break end end end return i end local function collapse_mn(di,i,data,ndata) -- this is tricky ... we need to make sure that we wrap in mrows if we want -- to bypass this one local collapsing = di.data if data then i = i + 1 while i <= ndata do local dn = data[i] local tg = dn.tg if tg == "mn" then collapsing[#collapsing+1] = dn.data[1] dn.skip = "ignore" i = i + 1 elseif tg == "mo" then local d = dn.data[1] if d == "." then collapsing[#collapsing+1] = d dn.skip = "ignore" i = i + 1 else break end else break end end end return i end -- maybe delay __i__ till we need it local apply_function = { { element = "mo", -- comment = "apply function", -- data = { utfchar(0x2061) }, data = { "&#x2061;" }, nature = "mixed", } } local functioncontent = { } setmetatableindex(functioncontent,function(t,k) local v = { { content = k } } t[k] = v return v end) local dummy_nucleus = { element = "mtext", data = { content = "" }, nature = "inline", comment = "dummy nucleus", fulltag = "mtext>0" } local function accentchar(d) for i=1,3 do d = d.data if not d then return end d = d[1] if not d then return end local tg = d.tg if tg == "mover" then local s = specifications[d.fulltag] local t = s.top if t then d = d.data[1] local d1 = d.data[1] d1.content = utfchar(t) d.data = { d1 } return d end elseif tg == "munder" then local s = specifications[d.fulltag] local b = s.bottom if b then d = d.data[1] local d1 = d.data[1] d1.content = utfchar(b) d.data = { d1 } return d end end end end local no_mrow = { mrow = true, mfenced = true, mfrac = true, mroot = true, msqrt = true, mi = true, mo = true, mn = true, } local function checkmath(root) -- we can provide utf.toentities as an option local data = root.data if data then local ndata = #data local roottg = root.tg if roottg == "msubsup" then local nucleus, superscript, subscript for i=1,ndata do local di = data[i] if not di then -- weird elseif di.content then -- text elseif not nucleus then nucleus = i elseif not superscript then superscript = i elseif not subscript then subscript = i else -- error end end if superscript and subscript then local sup, sub = data[superscript], data[subscript] data[superscript], data[subscript] = sub, sup -- sub.__o__, sup.__o__ = subscript, superscript sub.__i__, sup.__i__ = superscript, subscript end -- elseif roottg == "msup" or roottg == "msub" then -- -- m$^2$ -- if ndata == 1 then -- local d = data[1] -- data[2] = d -- d.__i__ = 2 -- data[1] = dummy_nucleus -- end elseif roottg == "mfenced" then local s = specifications[root.fulltag] local l, m, r = s.left, s.middle, s.right if l then l = utfchar(l) end if m then local t = { } for i=1,#m do t[i] = utfchar(m[i]) end m = concat(t) end if r then r = utfchar(r) end root.attributes = { open = l, separators = m, close = r, } end if ndata == 0 then return elseif ndata == 1 then local d = data[1] if not d then return elseif d.content then return elseif #root.data == 1 then local tg = d.tg if automathrows and roottg == "mrow" then -- maybe just always ! check spec first if no_mrow[tg] then root.skip = "comment" end elseif roottg == "mo" then if tg == "mo" then root.skip = "comment" end end end end local i = 1 while i <= ndata do -- -- -- TOO MUCH NESTED CHECKING -- -- -- local di = data[i] if di and not di.content then local tg = di.tg if tg == "math" then -- di.element = "mrow" -- when properties di.skip = "comment" checkmath(di) i = i + 1 elseif tg == "mover" then local s = specifications[di.fulltag] if s.accent then local t = s.top local d = di.data -- todo: accent = "false" (for scripts like limits) di.attributes = { accent = "true", } -- todo: p.topfixed if t then -- mover d[1].data[1].content = utfchar(t) di.data = { d[2], d[1] } end else -- can't happen end checkmath(di) i = i + 1 elseif tg == "munder" then local s = specifications[di.fulltag] if s.accent then local b = s.bottom local d = di.data -- todo: accent = "false" (for scripts like limits) di.attributes = { accent = "true", } -- todo: p.bottomfixed if b then -- munder d[2].data[1].content = utfchar(b) end else -- can't happen end checkmath(di) i = i + 1 elseif tg == "munderover" then local s = specifications[di.fulltag] if s.accent then local t = s.top local b = s.bottom local d = di.data -- todo: accent = "false" (for scripts like limits) -- todo: accentunder = "false" (for scripts like limits) di.attributes = { accent = "true", accentunder = "true", } -- todo: p.topfixed -- todo: p.bottomfixed if t and b then -- munderover d[1].data[1].content = utfchar(t) d[3].data[1].content = utfchar(b) di.data = { d[2], d[3], d[1] } else -- can't happen end else -- can't happen end checkmath(di) i = i + 1 elseif tg == "mstacker" then local d = di.data local d1 = d[1] local d2 = d[2] local d3 = d[3] local t1 = d1 and d1.tg local t2 = d2 and d2.tg local t3 = d3 and d3.tg local m = nil -- d1.data[1] local t = nil local b = nil -- only accent when top / bot have stretch -- normally we flush [base under over] which is better for tagged pdf if t1 == "mstackermid" then m = accentchar(d1) -- or m if t2 == "mstackertop" then if t3 == "mstackerbot" then t = accentchar(d2) b = accentchar(d3) di.element = "munderover" di.data = { m or d1.data[1], b or d3.data[1], t or d2.data[1] } else t = accentchar(d2) di.element = "mover" di.data = { m or d1.data[1], t or d2.data[1] } end elseif t2 == "mstackerbot" then if t3 == "mstackertop" then b = accentchar(d2) t = accentchar(d3) di.element = "munderover" di.data = { m or d1.data[1], t or d3.data[1], m, b or d2.data[1] } else b = accentchar(d2) di.element = "munder" di.data = { m or d1.data[1], b or d2.data[1] } end else -- can't happen end else -- can't happen end if t or b then di.attributes = { accent = t and "true" or nil, accentunder = b and "true" or nil, } di.detail = nil end checkmath(di) i = i + 1 elseif tg == "mroot" then local data = di.data local size = #data if size == 1 then -- else firefox complains ... code in math-tag (for pdf tagging) di.element = "msqrt" elseif size == 2 then data[1], data[2] = data[2], data[1] end checkmath(di) i = i + 1 elseif tg == "break" then di.skip = "comment" i = i + 1 elseif tg == "mtext" then -- this is only needed for unboxed mtexts ... all kind of special -- tex border cases and optimizations ... trial and error local data = di.data if #data > 1 then for i=1,#data do local di = data[i] local content = di.content if content then data[i] = { element = "mtext", nature = "inline", data = { di }, n = 0, } elseif di.tg == "math" then local di = di.data[1] data[i] = di checkmath(di) end end di.element = "mrow" -- di.tg = "mrow" -- di.nature = "inline" end checkmath(di) i = i + 1 elseif tg == "mrow" and detail then -- hm, falls through di.detail = nil checkmath(di) di = { element = "maction", nature = "display", attributes = { actiontype = detail }, data = { di }, n = 0, } data[i] = di i = i + 1 else local category = di.mathcategory if category then -- no checkmath(di) here if category == 1 then -- mo i = collapse(di,i,data,ndata,detail,"mo") elseif category == 2 then -- mi i = collapse(di,i,data,ndata,detail,"mi") elseif category == 3 then -- mn i = collapse(di,i,data,ndata,detail,"mn") elseif category == 4 then -- ms i = collapse(di,i,data,ndata,detail,"ms") elseif category >= 1000 then local apply = category >= 2000 if apply then category = category - 1000 end if tg == "mi" then -- function if roottg == "mrow" then root.skip = "comment" root.element = "function" end i = collapse(di,i,data,ndata,detail,"mi") local tag = functions[category] if tag then di.data = functioncontent[tag] end if apply then di.after = apply_function elseif automathapply then -- make function local following if i <= ndata then -- normally not the case following = data[i] else local parent = di.__p__ -- == root if parent.tg == "mrow" then parent = parent.__p__ end local index = parent.__i__ following = parent.data[index+1] end if following then local tg = following.tg if tg == "mrow" or tg == "mfenced" then -- we need to figure out the right condition di.after = apply_function end end end else -- some problem checkmath(di) i = i + 1 end else checkmath(di) i = i + 1 end elseif automathnumber and tg == "mn" then checkmath(di) i = collapse_mn(di,i,data,ndata) else checkmath(di) i = i + 1 end end else -- can be string or boolean if parenttg ~= "mtext" and di == " " then data[i] = false end i = i + 1 end end end end local function stripmath(di) if not di then -- elseif di.content then return di else local tg = di.tg if tg == "mtext" or tg == "ms" then return di else local data = di.data local ndata = #data local n = 0 for i=1,ndata do local d = data[i] if d and not d.content then d = stripmath(d) end if d then local content = d.content if not content then n = n + 1 d.__i__ = n data[n] = d elseif content == " " or content == "" then if di.tg == "mspace" then -- we append or prepend a space to a preceding or following mtext local parent = di.__p__ local index = di.__i__ -- == i local data = parent.data if index > 1 then local d = data[index-1] if d.tg == "mtext" then local dd = d.data local dn = dd[#dd] local dc = dn.content if dc then dn.content = dc .. content end end elseif index < ndata then local d = data[index+1] if d.tg == "mtext" then local dd = d.data local dn = dd[1] local dc = dn.content if dc then dn.content = content .. dc end end end end else n = n + 1 data[n] = d end end end for i=ndata,n+1,-1 do data[i] = nil end if #data > 0 then return di end -- end end -- could be integrated but is messy then -- while roottg == "mrow" and #data == 1 do -- data = data[1] -- for k, v in next, data do -- root[k] = v -- end -- roottg = data.tg -- end end end function checks.math(di) local specification = specifications[di.fulltag] local mode = specification and specification.mode == "display" and "block" or "inline" di.attributes = { ["display"] = mode, ["xmlns:m"] = mathmlns, } -- can be option if needed: if mode == "inline" then -- di.nature = "mixed" -- else spacing problem (maybe inline) di.nature = "inline" -- we need to catch x$X$x and x $X$ x else di.nature = "display" end if automathstrip then stripmath(di) end checkmath(di) end local a, z, A, Z = 0x61, 0x7A, 0x41, 0x5A function extras.mi(di,element,n,fulltag) -- check with content local str = di.data[1].content if str and sub(str,1,1) ~= "&" then -- hack but good enough (maybe gsub op eerste) for v in utfvalues(str) do if (v >= a and v <= z) or (v >= A and v <= Z) then local a = di.attributes if a then a.mathvariant = "normal" else di.attributes = { mathvariant = "normal" } end end end end end function extras.msub(di,element,n,fulltag) -- m$^2$ local data = di.data if #data == 1 then local d = data[1] data[2] = d d.__i__ = 2 data[1] = dummy_nucleus end end extras.msup = extras.msub end do local registered = structures.sections.registered local function resolve(di,element,n,fulltag) local data = listdata[fulltag] if data then extras.addreference(di,data.references) return true else local data = di.data if data then for i=1,#data do local di = data[i] if di then local ft = di.fulltag if ft and resolve(di,element,n,ft) then return true end end end end end end function extras.section(di,element,n,fulltag) local r = registered[specifications[fulltag].detail] if r then setattribute(di,"level",r.level) end resolve(di,element,n,fulltag) end extras.float = resolve -- todo: internal is already hashed function structurestags.setlist(n) local data = structures.lists.getresult(n) if data then referencehash[locatedtag("listitem")] = data end end function extras.listitem(di,element,n,fulltag) local data = referencehash[fulltag] if data then extras.addinternal(di,data.references) return true end end end do -- todo: internal is already hashed function structurestags.setregister(tag,n) -- check if tag is needed local data = structures.registers.get(tag,n) if data then referencehash[locatedtag("registerlocation")] = data end end function extras.registerlocation(di,element,n,fulltag) local data = referencehash[fulltag] if type(data) == "table" then extras.addinternal(di,data.references) return true else -- needs checking, probably bookmarks end end extras.registerpages = ignorebreaks extras.registerseparator = ignorespaces end do local tabledata = { } local function hascontent(data) for i=1,#data do local di = data[i] if not di then -- elseif di.content then return true else local d = di.data if d and #d > 0 and hascontent(d) then return true end end end end function structurestags.settablecell(rows,columns,align) if align > 0 or rows > 1 or columns > 1 then tabledata[locatedtag("tablecell")] = { rows = rows, columns = columns, align = align, } end end function extras.tablecell(di,element,n,fulltag) local hash = tabledata[fulltag] if hash then local columns = hash.columns if columns and columns > 1 then setattribute(di,"columns",columns) end local rows = hash.rows if rows and rows > 1 then setattribute(di,"rows",rows) end local align = hash.align if not align or align == 0 then -- normal elseif align == 1 then -- use numbertoalign here setattribute(di,"align","flushright") elseif align == 2 then setattribute(di,"align","middle") elseif align == 3 then setattribute(di,"align","flushleft") end end end local tabulatedata = { } function structurestags.settabulatecell(align) if align > 0 then tabulatedata[locatedtag("tabulatecell")] = { align = align, } end end function extras.tabulate(di,element,n,fulltag) local data = di.data for i=1,#data do local di = data[i] if di.tg == "tabulaterow" and not hascontent(di.data) then di.element = "" -- or simply remove end end end function extras.tabulatecell(di,element,n,fulltag) local hash = tabulatedata[fulltag] if hash then local align = hash.align if not align or align == 0 then -- normal elseif align == 1 then setattribute(di,"align","flushleft") elseif align == 2 then setattribute(di,"align","flushright") elseif align == 3 then setattribute(di,"align","middle") end end end end -- flusher do local f_detail = formatters[' detail="%s"'] local f_chain = formatters[' chain="%s"'] local f_index = formatters[' n="%s"'] local f_spacing = formatters['<c n="%s">%s</c>'] local f_empty_inline = formatters["<%s/>"] local f_empty_mixed = formatters["%w<%s/>\n"] local f_empty_display = formatters["\n%w<%s/>\n"] local f_empty_inline_attr = formatters["<%s%s/>"] local f_empty_mixed_attr = formatters["%w<%s%s/>"] local f_empty_display_attr = formatters["\n%w<%s%s/>\n"] local f_begin_inline = formatters["<%s>"] local f_begin_mixed = formatters["%w<%s>"] local f_begin_display = formatters["\n%w<%s>\n"] local f_begin_inline_attr = formatters["<%s%s>"] local f_begin_mixed_attr = formatters["%w<%s%s>"] local f_begin_display_attr = formatters["\n%w<%s%s>\n"] local f_end_inline = formatters["</%s>"] local f_end_mixed = formatters["</%s>\n"] local f_end_display = formatters["%w</%s>\n"] local f_begin_inline_comment = formatters["<!-- %s --><%s>"] local f_begin_mixed_comment = formatters["%w<!-- %s --><%s>"] local f_begin_display_comment = formatters["\n%w<!-- %s -->\n%w<%s>\n"] local f_begin_inline_attr_comment = formatters["<!-- %s --><%s%s>"] local f_begin_mixed_attr_comment = formatters["%w<!-- %s --><%s%s>"] local f_begin_display_attr_comment = formatters["\n%w<!-- %s -->\n%w<%s%s>\n"] local f_comment_begin_inline = formatters["<!-- begin %s -->"] local f_comment_begin_mixed = formatters["%w<!-- begin %s -->"] local f_comment_begin_display = formatters["\n%w<!-- begin %s -->\n"] local f_comment_end_inline = formatters["<!-- end %s -->"] local f_comment_end_mixed = formatters["<!-- end %s -->\n"] local f_comment_end_display = formatters["%w<!-- end %s -->\n"] local f_metadata_begin = formatters["\n%w<metadata>\n"] local f_metadata = formatters["%w<metavariable name=%q>%s</metavariable>\n"] local f_metadata_end = formatters["%w</metadata>\n"] --- we could share the r tables ... but it's fast enough anyway local function attributes(a) local r = { } -- can be shared local n = 0 for k, v in next, a do n = n + 1 r[n] = f_attribute(k,v) -- lpegmatch(p_escaped,v) end return concat(r,"",1,n) end local depth = 0 local inline = 0 local function bpar(result) result[#result+1] = "\n<p>" end local function epar(result) result[#result+1] = "</p>\n" end local function emptytag(result,embedded,element,nature,di) -- currently only break but at some point local a = di.attributes -- we might add detail etc if a then -- happens seldom if nature == "display" then result[#result+1] = f_empty_display_attr(depth,namespaced[element],attributes(a)) elseif nature == "mixed" then result[#result+1] = f_empty_mixed_attr(depth,namespaced[element],attributes(a)) else result[#result+1] = f_empty_inline_attr(namespaced[element],attributes(a)) end else if nature == "display" then result[#result+1] = f_empty_display(depth,namespaced[element]) elseif nature == "mixed" then result[#result+1] = f_empty_mixed(depth,namespaced[element]) else result[#result+1] = f_empty_inline(namespaced[element]) end end end local function begintag(result,embedded,element,nature,di,skip) local index = di.n local fulltag = di.fulltag local specification = specifications[fulltag] or { } -- we can have a dummy local comment = di.comment local detail = specification.detail if skip == "comment" then if show_comment then if nature == "inline" or inline > 0 then result[#result+1] = f_comment_begin_inline(namespaced[element]) inline = inline + 1 elseif nature == "mixed" then result[#result+1] = f_comment_begin_mixed(depth,namespaced[element]) depth = depth + 1 inline = 1 else result[#result+1] = f_comment_begin_display(depth,namespaced[element]) depth = depth + 1 end end elseif skip then -- ignore else -- if embedded then -- if element == "math" then -- embedded[f_tagid(element,index)] = #result+1 -- end -- end local n = 0 local r = { } -- delay this if detail then detail = gsub(detail,"[^A-Za-z0-9]+","-") specification.detail = detail -- we use it later in for the div n = n + 1 r[n] = f_detail(detail) end local parents = specification.parents if parents then parents = gsub(parents,"[^A-Za-z0-9 ]+","-") specification.parents = parents -- we use it later in for the div n = n + 1 r[n] = f_chain(parents) end if indexing and index then n = n + 1 r[n] = f_index(index) end local extra = extras[element] if extra then extra(di,element,index,fulltag) end if exportproperties then local p = specification.userdata if not p then -- skip elseif exportproperties == v_yes then for k, v in next, p do n = n + 1 r[n] = f_attribute(k,v) end else for k, v in next, p do n = n + 1 r[n] = f_property(exportproperties,k,v) end end end local a = di.attributes if a then for k, v in next, a do n = n + 1 r[n] = f_attribute(k,v) end end if n == 0 then if nature == "inline" or inline > 0 then if show_comment and comment then result[#result+1] = f_begin_inline_comment(comment,namespaced[element]) else result[#result+1] = f_begin_inline(namespaced[element]) end inline = inline + 1 elseif nature == "mixed" then if show_comment and comment then result[#result+1] = f_begin_mixed_comment(depth,comment,namespaced[element]) else result[#result+1] = f_begin_mixed(depth,namespaced[element]) end depth = depth + 1 inline = 1 else if show_comment and comment then result[#result+1] = f_begin_display_comment(depth,comment,depth,namespaced[element]) else result[#result+1] = f_begin_display(depth,namespaced[element]) end depth = depth + 1 end else r = concat(r,"",1,n) if nature == "inline" or inline > 0 then if show_comment and comment then result[#result+1] = f_begin_inline_attr_comment(comment,namespaced[element],r) else result[#result+1] = f_begin_inline_attr(namespaced[element],r) end inline = inline + 1 elseif nature == "mixed" then if show_comment and comment then result[#result+1] = f_begin_mixed_attr_comment(depth,comment,namespaced[element],r) else result[#result+1] = f_begin_mixed_attr(depth,namespaced[element],r) end depth = depth + 1 inline = 1 else if show_comment and comment then result[#result+1] = f_begin_display_attr_comment(depth,comment,depth,namespaced[element],r) else result[#result+1] = f_begin_display_attr(depth,namespaced[element],r) end depth = depth + 1 end end end used[element][detail or ""] = { nature, specification.parents } -- for template css -- also in last else ? local metadata = specification.metadata if metadata then result[#result+1] = f_metadata_begin(depth) for k, v in table.sortedpairs(metadata) do result[#result+1] = f_metadata(depth+1,k,lpegmatch(p_entity,v)) end result[#result+1] = f_metadata_end(depth) end end local function endtag(result,embedded,element,nature,di,skip) if skip == "comment" then if show_comment then if nature == "display" and (inline == 0 or inline == 1) then depth = depth - 1 result[#result+1] = f_comment_end_display(depth,namespaced[element]) inline = 0 elseif nature == "mixed" and (inline == 0 or inline == 1) then depth = depth - 1 result[#result+1] = f_comment_end_mixed(namespaced[element]) inline = 0 else inline = inline - 1 result[#result+1] = f_comment_end_inline(namespaced[element]) end end elseif skip then -- ignore else if nature == "display" and (inline == 0 or inline == 1) then depth = depth - 1 result[#result+1] = f_end_display(depth,namespaced[element]) inline = 0 elseif nature == "mixed" and (inline == 0 or inline == 1) then depth = depth - 1 result[#result+1] = f_end_mixed(namespaced[element]) inline = 0 else inline = inline - 1 result[#result+1] = f_end_inline(namespaced[element]) end -- if embedded then -- if element == "math" then -- local id = f_tagid(element,di.n) -- index) -- local tx = concat(result,"",embedded[id],#result) -- embedded[id] = "<?xml version='1.0' standalone='yes'?>" .. "\n" .. tx -- end -- end end end local function flushtree(result,embedded,data,nature) local nofdata = #data for i=1,nofdata do local di = data[i] if not di then -- hm, di can be string -- whatever else local content = di.content -- also optimize for content == "" : trace that first if content then -- already has breaks local content = lpegmatch(p_entity,content) if i == nofdata and sub(content,-1) == "\n" then -- move check -- can be an end of line in par but can also be the last line if trace_spacing then result[#result+1] = f_spacing(di.parnumber or 0,sub(content,1,-2)) else result[#result+1] = sub(content,1,-2) end result[#result+1] = " " else if trace_spacing then result[#result+1] = f_spacing(di.parnumber or 0,content) else result[#result+1] = content end end elseif not di.collapsed then -- ignore collapsed data (is appended, reconstructed par) local element = di.element if not element then -- skip elseif element == "break" then -- or element == "pagebreak" emptytag(result,embedded,element,nature,di) elseif element == "" or di.skip == "ignore" then -- skip else if di.before then flushtree(result,embedded,di.before,nature) end local natu = di.nature local skip = di.skip if di.breaknode then emptytag(result,embedded,"break","display",di) end begintag(result,embedded,element,natu,di,skip) flushtree(result,embedded,di.data,natu) endtag(result,embedded,element,natu,di,skip) if di.after then flushtree(result,embedded,di.after,nature) end end end end end end local function breaktree(tree,parent,parentelement) -- also removes double breaks local data = tree.data if data then local nofdata = #data local prevelement local prevnature local prevparnumber local newdata = { } local nofnewdata = 0 for i=1,nofdata do local di = data[i] if not di then -- skip elseif di.content then local parnumber = di.parnumber if prevnature == "inline" and prevparnumber and prevparnumber ~= parnumber then nofnewdata = nofnewdata + 1 if trace_spacing then newdata[nofnewdata] = makebreaknode { type = "a", p = prevparnumber, n = parnumber } else newdata[nofnewdata] = makebreaknode() end end prevelement = nil prevnature = "inline" prevparnumber = parnumber nofnewdata = nofnewdata + 1 newdata[nofnewdata] = di elseif not di.collapsed then local element = di.element if element == "break" then -- or element == "pagebreak" if prevelement == "break" then di.element = "" end prevelement = element prevnature = "display" elseif element == "" or di.skip == "ignore" then -- skip else local nature = di.nature local parnumber = di.parnumber if prevnature == "inline" and nature == "inline" and prevparnumber and prevparnumber ~= parnumber then nofnewdata = nofnewdata + 1 if trace_spacing then newdata[nofnewdata] = makebreaknode { type = "b", p = prevparnumber, n = parnumber } else newdata[nofnewdata] = makebreaknode() end end prevnature = nature prevparnumber = parnumber prevelement = element breaktree(di,tree,element) end nofnewdata = nofnewdata + 1 newdata[nofnewdata] = di else local nature = di.nature local parnumber = di.parnumber if prevnature == "inline" and nature == "inline" and prevparnumber and prevparnumber ~= parnumber then nofnewdata = nofnewdata + 1 if trace_spacing then newdata[nofnewdata] = makebreaknode { type = "c", p = prevparnumber, n = parnumber } else newdata[nofnewdata] = makebreaknode() end end prevnature = nature prevparnumber = parnumber nofnewdata = nofnewdata + 1 newdata[nofnewdata] = di end end tree.data = newdata end end -- also tabulaterow reconstruction .. maybe better as a checker -- i.e cell attribute local function collapsetree() for tag, trees in next, treehash do local d = trees[1].data if d then local nd = #d if nd > 0 then for i=2,#trees do local currenttree = trees[i] local currentdata = currenttree.data local currentpar = currenttree.parnumber local previouspar = trees[i-1].parnumber currenttree.collapsed = true -- is the next ok? if previouspar == 0 or not (di and di.content) then previouspar = nil -- no need anyway so no further testing needed end for j=1,#currentdata do local cd = currentdata[j] if not cd or cd == "" then -- skip elseif cd.content then if not currentpar then -- add space ? elseif not previouspar then -- add space ? elseif currentpar ~= previouspar then nd = nd + 1 if trace_spacing then d[nd] = makebreaknode { type = "d", p = previouspar, n = currentpar } else d[nd] = makebreaknode() end end previouspar = currentpar nd = nd + 1 d[nd] = cd else nd = nd + 1 d[nd] = cd end currentdata[j] = false end end end end end end local function finalizetree(tree) for _, finalizer in next, finalizers do finalizer(tree) end end local function indextree(tree) local data = tree.data if data then local n, new = 0, { } for i=1,#data do local d = data[i] if not d then -- skip elseif d.content then n = n + 1 new[n] = d elseif not d.collapsed then n = n + 1 d.__i__ = n d.__p__ = tree indextree(d) new[n] = d end end tree.data = new end end local function checktree(tree) local data = tree.data if data then for i=1,#data do local d = data[i] if type(d) == "table" then local check = checks[d.tg] if check then check(d) end checktree(d) end end end end wrapups.flushtree = flushtree wrapups.breaktree = breaktree wrapups.collapsetree = collapsetree wrapups.finalizetree = finalizetree wrapups.indextree = indextree wrapups.checktree = checktree end -- collector code local function push(fulltag,depth) local tg, n, detail local specification = specifications[fulltag] if specification then tg = specification.tagname n = specification.tagindex detail = specification.detail else -- a break (more efficient if we don't store those in specifications) tg, n = lpegmatch(tagsplitter,fulltag) n = tonumber(n) -- to tonumber in tagsplitter end local p = properties[tg] local element = p and p.export or tg local nature = p and p.nature or "inline" -- defaultnature local treedata = tree.data local t = { -- maybe we can use the tag table tg = tg, fulltag = fulltag, detail = detail, n = n, -- already a number element = element, nature = nature, data = { }, attribute = currentattribute, parnumber = currentparagraph, } treedata[#treedata+1] = t currentdepth = currentdepth + 1 nesting[currentdepth] = fulltag treestack[currentdepth] = tree if trace_export then if detail and detail ~= "" then report_export("%w<%s trigger=%q n=%q paragraph=%q index=%q detail=%q>",currentdepth-1,tg,n,currentattribute or 0,currentparagraph or 0,#treedata,detail) else report_export("%w<%s trigger=%q n=%q paragraph=%q index=%q>",currentdepth-1,tg,n,currentattribute or 0,currentparagraph or 0,#treedata) end end tree = t if tg == "break" then -- no need for this else local h = treehash[fulltag] if h then h[#h+1] = t else treehash[fulltag] = { t } end end end local function pop() if currentdepth > 0 then local top = nesting[currentdepth] tree = treestack[currentdepth] currentdepth = currentdepth - 1 if trace_export then if top then report_export("%w</%s>",currentdepth,top) else report_export("</%s>",top) end end else report_export("%w<!-- too many pops -->",currentdepth) end end local function continueexport() if nofcurrentcontent > 0 then if trace_export then report_export("%w<!-- injecting pagebreak space -->",currentdepth) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " -- pagebreak end end local function pushentry(current) if not current then -- bad news return end current = current.taglist if not current then -- even worse news return end if restart then continueexport() restart = false end local newdepth = #current local olddepth = currentdepth if trace_export then report_export("%w<!-- moving from depth %s to %s (%s) -->",currentdepth,olddepth,newdepth,current[newdepth]) end if olddepth <= 0 then for i=1,newdepth do push(current[i],i) end else local difference if olddepth < newdepth then for i=1,olddepth do if current[i] ~= nesting[i] then difference = i break end end else for i=1,newdepth do if current[i] ~= nesting[i] then difference = i break end end end if difference then for i=olddepth,difference,-1 do pop() end for i=difference,newdepth do push(current[i],i) end elseif newdepth > olddepth then for i=olddepth+1,newdepth do push(current[i],i) end elseif newdepth < olddepth then for i=olddepth,newdepth,-1 do pop() end elseif trace_export then report_export("%w<!-- staying at depth %s (%s) -->",currentdepth,newdepth,nesting[newdepth] or "?") end end return olddepth, newdepth end local function pushcontent(oldparagraph,newparagraph) if nofcurrentcontent > 0 then if oldparagraph then if currentcontent[nofcurrentcontent] == "\n" then if trace_export then report_export("%w<!-- removing newline -->",currentdepth) end nofcurrentcontent = nofcurrentcontent - 1 end end local content = concat(currentcontent,"",1,nofcurrentcontent) if content == "" then -- omit; when oldparagraph we could push, remove spaces, pop elseif somespace[content] and oldparagraph then -- omit; when oldparagraph we could push, remove spaces, pop else local olddepth, newdepth local list = taglist[currentattribute] if list then olddepth, newdepth = pushentry(list) end if tree then local td = tree.data local nd = #td td[nd+1] = { parnumber = oldparagraph or currentparagraph, content = content } if trace_export then report_export("%w<!-- start content with length %s -->",currentdepth,#content) report_export("%w%s",currentdepth,(gsub(content,"\n","\\n"))) report_export("%w<!-- stop content -->",currentdepth) end if olddepth then for i=newdepth-1,olddepth,-1 do pop() end end end end nofcurrentcontent = 0 end if oldparagraph then pushentry(makebreaklist(currentnesting)) if trace_export then report_export("%w<!-- break added between paragraph %a and %a -->",currentdepth,oldparagraph,newparagraph) end end end local function finishexport() if trace_export then report_export("%w<!-- start finalizing -->",currentdepth) end if nofcurrentcontent > 0 then if somespace[currentcontent[nofcurrentcontent]] then if trace_export then report_export("%w<!-- removing space -->",currentdepth) end nofcurrentcontent = nofcurrentcontent - 1 end pushcontent() end for i=currentdepth,1,-1 do pop() end currentcontent = { } -- we're nice and do a cleanup if trace_export then report_export("%w<!-- stop finalizing -->",currentdepth) end end local function collectresults(head,list,pat,pap) -- is last used (we also have currentattribute) local p for n in traverse_nodes(head) do local c, id = isglyph(n) -- 14: image, 8: literal (mp) if c then local at = getattr(n,a_tagged) or pat if not at then -- we need to tag the pagebody stuff as being valid skippable -- -- report_export("skipping character: %C (no attribute)",n.char) else -- we could add tonunicodes for ligatures (todo) local components = getfield(n,"components") if components and (not characterdata[c] or overloads[c]) then -- we loose data collectresults(components,nil,at) -- this assumes that components have the same attribute as the glyph ... we should be more tolerant (see math) else if last ~= at then local tl = taglist[at] pushcontent() currentnesting = tl currentparagraph = getattr(n,a_taggedpar) or pap currentattribute = at last = at pushentry(currentnesting) if trace_export then report_export("%w<!-- processing glyph %C tagged %a -->",currentdepth,c,at) end -- We need to intercept this here; maybe I will also move this -- to a regular setter at the tex end. local r = getattr(n,a_reference) if r then local t = tl.taglist referencehash[t[#t]] = r -- fulltag end -- elseif last then -- we can consider tagging the pars (lines) in the parbuilder but then we loose some -- information unless we inject a special node (but even then we can run into nesting -- issues) local ap = getattr(n,a_taggedpar) or pap if ap ~= currentparagraph then pushcontent(currentparagraph,ap) pushentry(currentnesting) currentattribute = last currentparagraph = ap end if trace_export then report_export("%w<!-- processing glyph %C tagged %a) -->",currentdepth,c,last) end else if trace_export then report_export("%w<!-- processing glyph %C tagged %a) -->",currentdepth,c,at) end end local s = getattr(n,a_exportstatus) if s then c = s end if c == 0 then if trace_export then report_export("%w<!-- skipping last glyph -->",currentdepth) end elseif c == 0x20 then local a = getattr(n,a_characters) nofcurrentcontent = nofcurrentcontent + 1 if a then if trace_export then report_export("%w<!-- turning last space into special space %U -->",currentdepth,a) end currentcontent[nofcurrentcontent] = specialspaces[a] -- special space else currentcontent[nofcurrentcontent] = " " end else local fc = fontchar[getfont(n)] if fc then fc = fc and fc[c] if fc then local u = fc.unicode if not u then nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = utfchar(c) elseif type(u) == "table" then for i=1,#u do nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = utfchar(u[i]) end else nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = utfchar(u) end elseif c > 0 then nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = utfchar(c) else -- we can have -1 as side effect of an explicit hyphen (unless we expand) end elseif c > 0 then nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = utfchar(c) else -- we can have -1 as side effect of an explicit hyphen (unless we expand) end end end end elseif id == disc_code then -- probably too late local pre, post, replace = getdisc(n) if keephyphens then if pre and not getnext(pre) and isglyph(pre) == hyphencode then nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = hyphen end end if replace then collectresults(replace,nil) end elseif id == glue_code then -- we need to distinguish between hskips and vskips local ca = getattr(n,a_characters) if ca == 0 then -- skip this one ... already converted special character (node-acc) elseif ca then local a = getattr(n,a_tagged) or pat if a then local c = specialspaces[ca] if last ~= a then local tl = taglist[a] if trace_export then report_export("%w<!-- processing space glyph %U tagged %a case 1 -->",currentdepth,ca,a) end pushcontent() currentnesting = tl currentparagraph = getattr(n,a_taggedpar) or pap currentattribute = a last = a pushentry(currentnesting) -- no reference check (see above) elseif last then local ap = getattr(n,a_taggedpar) or pap if ap ~= currentparagraph then pushcontent(currentparagraph,ap) pushentry(currentnesting) currentattribute = last currentparagraph = ap end if trace_export then report_export("%w<!-- processing space glyph %U tagged %a case 2 -->",currentdepth,ca,last) end end -- if somespace[currentcontent[nofcurrentcontent]] then -- if trace_export then -- report_export("%w<!-- removing space -->",currentdepth) -- end -- nofcurrentcontent = nofcurrentcontent - 1 -- end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = c end else local subtype = getsubtype(n) if subtype == userskip_code then if getfield(n,"width") > threshold then if last and not somespace[currentcontent[nofcurrentcontent]] then local a = getattr(n,a_tagged) or pat if a == last then if trace_export then report_export("%w<!-- injecting spacing 5a -->",currentdepth) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " elseif a then -- e.g LOGO<space>LOGO if trace_export then report_export("%w<!-- processing glue > threshold tagged %s becomes %s -->",currentdepth,last,a) end pushcontent() if trace_export then report_export("%w<!-- injecting spacing 5b -->",currentdepth) end last = a nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " currentnesting = taglist[last] pushentry(currentnesting) currentattribute = last end end end elseif subtype == spaceskip_code or subtype == xspaceskip_code then if not somespace[currentcontent[nofcurrentcontent]] then local a = getattr(n,a_tagged) or pat if a == last then if trace_export then report_export("%w<!-- injecting spacing 7 (stay in element) -->",currentdepth) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " else if trace_export then report_export("%w<!-- injecting spacing 7 (end of element) -->",currentdepth) end last = a pushcontent() nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " currentnesting = taglist[last] pushentry(currentnesting) currentattribute = last end end elseif subtype == rightskip_code then -- a line if nofcurrentcontent > 0 then local r = currentcontent[nofcurrentcontent] if r == hyphen then if not keephyphens then nofcurrentcontent = nofcurrentcontent - 1 end elseif not somespace[r] then local a = getattr(n,a_tagged) or pat if a == last then if trace_export then report_export("%w<!-- injecting spacing 1 (end of line, stay in element) -->",currentdepth) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " else if trace_export then report_export("%w<!-- injecting spacing 1 (end of line, end of element) -->",currentdepth) end last = a pushcontent() nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " currentnesting = taglist[last] pushentry(currentnesting) currentattribute = last end end end elseif subtype == parfillskip_code then -- deal with paragaph endings (crossings) elsewhere and we quit here -- as we don't want the rightskip space addition return end end elseif id == hlist_code or id == vlist_code then local ai = getattr(n,a_image) if ai then local at = getattr(n,a_tagged) or pat if nofcurrentcontent > 0 then pushcontent() pushentry(currentnesting) -- ?? end pushentry(taglist[at]) -- has an index, todo: flag empty element if trace_export then report_export("%w<!-- processing image tagged %a",currentdepth,last) end last = nil currentparagraph = nil else -- we need to determine an end-of-line local list = getlist(n) if list then local at = getattr(n,a_tagged) or pat collectresults(list,n,at) end end elseif id == kern_code then local kern = getfield(n,"kern") if kern > 0 then local limit = threshold if p and getid(p) == glyph_code then limit = fontquads[getfont(p)] / 4 end if kern > limit then if last and not somespace[currentcontent[nofcurrentcontent]] then local a = getattr(n,a_tagged) or pat if a == last then if not somespace[currentcontent[nofcurrentcontent]] then if trace_export then report_export("%w<!-- injecting spacing 8 (kern %p) -->",currentdepth,kern) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " end elseif a then -- e.g LOGO<space>LOGO if trace_export then report_export("%w<!-- processing kern, threshold %p, tag %s => %s -->",currentdepth,limit,last,a) end last = a pushcontent() if trace_export then report_export("%w<!-- injecting spacing 9 (kern %p) -->",currentdepth,kern) end nofcurrentcontent = nofcurrentcontent + 1 currentcontent[nofcurrentcontent] = " " currentnesting = taglist[last] pushentry(currentnesting) currentattribute = last end end end end end p = n end end function nodes.handlers.export(head) -- hooks into the page builder starttiming(treehash) if trace_export then report_export("%w<!-- start flushing page -->",currentdepth) end -- continueexport() restart = true -- local function f(head,depth,pat) -- for n in node.traverse(head) do -- local a = n[a_tagged] or pat -- local t = taglist[a] -- print(depth,n,a,t and table.concat(t," ")) -- if n.id == hlist_code or n.id == vlist_code and n.list then -- f(n.list,depth+1,a) -- end -- end -- end -- f(head,1) collectresults(tonut(head)) if trace_export then report_export("%w<!-- stop flushing page -->",currentdepth) end stoptiming(treehash) return head, true end function builders.paragraphs.tag(head) noftextblocks = noftextblocks + 1 for n in traverse_id(hlist_code,tonut(head)) do local subtype = getsubtype(n) if subtype == line_code then setattr(n,a_textblock,noftextblocks) elseif subtype == glue_code or subtype == kern_code then setattr(n,a_textblock,0) end end return false end do local xmlpreamble = [[ <?xml version="1.0" encoding="UTF-8" standalone="%standalone%" ?> <!-- input filename : %filename% processing date : %date% context version : %contextversion% exporter version : %exportversion% --> ]] local flushtree = wrapups.flushtree local function wholepreamble(standalone) return replacetemplate(xmlpreamble, { standalone = standalone and "yes" or "no", filename = tex.jobname, date = os.date(), contextversion = environment.version, exportversion = exportversion, }) end local csspreamble = [[ <?xml-stylesheet type="text/css" href="%filename%" ?> ]] local cssheadlink = [[ <link type="text/css" rel="stylesheet" href="%filename%" /> ]] local function allusedstylesheets(cssfiles,files,path) local done = { } local result = { } local extras = { } for i=1,#cssfiles do local cssfile = cssfiles[i] if type(cssfile) ~= "string" then -- error elseif cssfile == "export-example.css" then -- ignore elseif not done[cssfile] then cssfile = file.join(path,cssfile) report_export("adding css reference '%s'",cssfile) files[#files+1] = cssfile result[#result+1] = replacetemplate(csspreamble, { filename = cssfile }) extras[#extras+1] = replacetemplate(cssheadlink, { filename = cssfile }) done[cssfile] = true end end return concat(result), concat(extras) end local elementtemplate = [[ /* element="%element%" detail="%detail%" chain="%chain%" */ %element%, %namespace%div.%element% { display: %display% ; }]] local detailtemplate = [[ /* element="%element%" detail="%detail%" chain="%chain%" */ %element%[detail=%detail%], %namespace%div.%element%.%detail% { display: %display% ; }]] -- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd" > local htmltemplate = [[ %preamble% <html xmlns="http://www.w3.org/1999/xhtml" xmlns:math="http://www.w3.org/1998/Math/MathML"> <head> <meta charset="utf-8"/> <title>%title%</title> %style% </head> <body> <div xmlns="http://www.pragma-ade.com/context/export"> <div class="warning">Rendering can be suboptimal because there is no default/fallback css loaded.</div> %body% </div> </body> </html> ]] local displaymapping = { inline = "inline", display = "block", mixed = "inline", } local function allusedelements(basename) local result = { replacetemplate(namespacetemplate, { what = "template", filename = basename, namespace = contextns, -- cssnamespaceurl = usecssnamespace and cssnamespaceurl or "", cssnamespaceurl = cssnamespaceurl, }) } for element, details in sortedhash(used) do if namespaces[element] then -- skip math else for detail, what in sortedhash(details) do local nature = what[1] or "display" local chain = what[2] local display = displaymapping[nature] or "block" if detail == "" then result[#result+1] = replacetemplate(elementtemplate, { element = element, display = display, chain = chain, namespace = usecssnamespace and namespace or "", }) else result[#result+1] = replacetemplate(detailtemplate, { element = element, display = display, detail = detail, chain = chain, namespace = usecssnamespace and cssnamespace or "", }) end end end end return concat(result,"\n\n") end local function allcontent(tree,embed) local result = { } local embedded = embed and { } flushtree(result,embedded,tree.data,"display") -- we need to collect images result = concat(result) -- no need to lpeg .. fast enough result = gsub(result,"\n *\n","\n") result = gsub(result,"\n +([^< ])","\n%1") return result, embedded end -- local xhtmlpreamble = [[ -- <!DOCTYPE html PUBLIC -- "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" -- "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd" -- > -- ]] local function cleanxhtmltree(xmltree) if xmltree then local implicits = { } local explicits = { } local overloads = { } for e in xml.collected(xmltree,"*") do local at = e.at if at then local explicit = at.explicit local implicit = at.implicit if explicit then if not explicits[explicit] then explicits[explicit] = true at.id = explicit if implicit then overloads[implicit] = explicit end end else if implicit and not implicits[implicit] then implicits[implicit] = true at.id = "aut:" .. implicit end end end end for e in xml.collected(xmltree,"*") do local at = e.at if at then local internal = at.internal local location = at.location if internal then if location then local explicit = overloads[location] if explicit then at.href = "#" .. explicit else at.href = "#aut:" .. internal end else at.href = "#aut:" .. internal end else if location then at.href = "#" .. location else local url = at.url if url then at.href = url else local file = at.file if file then at.href = file end end end end end end return xmltree else return xml.convert('<?xml version="1.0"?>\n<error>invalid xhtml tree</error>') end end -- maybe the reverse: be explicit about what is permitted local private = { destination = true, prefix = true, reference = true, -- id = true, href = true, -- implicit = true, explicit = true, -- url = true, file = true, internal = true, location = true, -- name = true, -- image name used = true, -- image name page = true, -- image name width = true, height = true, -- } local addclicks = true local f_onclick = formatters[ [[location.href='%s']] ] local f_onclick = formatters[ [[location.href='%s']] ] local p_cleanid = lpeg.replacer { [":"] = "-" } local p_cleanhref = lpeg.Cs(lpeg.P("#") * p_cleanid) local p_splitter = lpeg.Ct ( ( lpeg.Carg(1) * lpeg.C((1-lpeg.P(" "))^1) / function(d,s) if not d[s] then d[s] = true return s end end * lpeg.P(" ")^0 )^1 ) local classes = table.setmetatableindex(function(t,k) local v = concat(lpegmatch(p_splitter,k,1,{})," ") t[k] = v return v end) local function makeclass(tg,at) local detail = at.detail local chain = at.chain local result at.detail = nil at.chain = nil if detail and detail ~= "" then if chain and chain ~= "" then if chain ~= detail then result = { classes[tg .. " " .. chain .. " " .. detail] } -- we need to remove duplicates elseif tg ~= detail then result = { tg, detail } else result = { tg } end elseif tg ~= detail then result = { tg, detail } else result = { tg } end elseif chain and chain ~= "" then if tg ~= chain then result = { tg, chain } else result = { tg } end else result = { tg } end for k, v in next, at do if not private[k] then result[#result+1] = k .. "-" .. v end end return concat(result, " ") end local function remap(specification,source,target) local comment = nil -- share comments for c in xml.collected(source,"*") do if not c.special then local tg = c.tg local ns = c.ns if ns == "m" then if false then -- yes or no c.ns = "" c.at["xmlns:m"] = nil end -- elseif tg == "a" then -- c.ns = "" else -- if tg == "tabulatecell" or tg == "tablecell" then local dt = c.dt local nt = #dt if nt == 0 or (nt == 1 and dt[1] == "") then if comment then c.dt = comment else xml.setcomment(c,"empty") comment = c.dt end end -- end local at = c.at local class = nil if tg == "document" then at.href = nil at.detail = nil at.chain = nil elseif tg == "metavariable" then at.detail = "metaname-" .. at.name class = makeclass(tg,at) else class = makeclass(tg,at) end local id = at.id local href = at.href if id then id = lpegmatch(p_cleanid, id) or id if href then href = lpegmatch(p_cleanhref,href) or href c.at = { class = class, id = id, href = href, onclick = addclicks and f_onclick(href) or nil, } else c.at = { class = class, id = id, } end else if href then href = lpegmatch(p_cleanhref,href) or href c.at = { class = class, href = href, onclick = addclicks and f_onclick(href) or nil, } else c.at = { class = class, } end end c.tg = "div" end end end end -- local cssfile = nil directives.register("backend.export.css", function(v) cssfile = v end) local addsuffix = file.addsuffix local joinfile = file.join local embedfile = false directives.register("export.embed",function(v) embedfile = v end) local embedmath = false local function stopexport(v) starttiming(treehash) -- finishexport() -- report_export("") report_export("exporting xml, xhtml and html files") report_export("") -- wrapups.collapsetree(tree) wrapups.indextree(tree) wrapups.checktree(tree) wrapups.breaktree(tree) wrapups.finalizetree(tree) -- wrapups.hashlistdata() -- if type(v) ~= "string" or v == v_yes or v == "" then v = tex.jobname end -- we use a dedicated subpath: -- -- ./jobname-export -- ./jobname-export/images -- ./jobname-export/styles -- ./jobname-export/styles -- ./jobname-export/jobname-export.xml -- ./jobname-export/jobname-export.xhtml -- ./jobname-export/jobname-export.html -- ./jobname-export/jobname-specification.lua -- ./jobname-export/styles/jobname-defaults.css -- ./jobname-export/styles/jobname-styles.css -- ./jobname-export/styles/jobname-images.css -- ./jobname-export/styles/jobname-templates.css local basename = file.basename(v) local basepath = basename .. "-export" local imagepath = joinfile(basepath,"images") local stylepath = joinfile(basepath,"styles") local function validpath(what,pathname) if lfs.isdir(pathname) then report_export("using exiting %s path %a",what,pathname) return pathname end lfs.mkdir(pathname) if lfs.isdir(pathname) then report_export("using cretated %s path %a",what,basepath) return pathname else report_export("unable to create %s path %a",what,basepath) return false end end if not (validpath("export",basepath) and validpath("images",imagepath) and validpath("styles",stylepath)) then return end -- we're now on the dedicated export subpath so we can't clash names local xmlfilebase = addsuffix(basename .. "-raw","xml" ) local xhtmlfilebase = addsuffix(basename .. "-tag","xhtml") local htmlfilebase = addsuffix(basename .. "-div","xhtml") local specificationfilebase = addsuffix(basename .. "-pub","lua" ) local xmlfilename = joinfile(basepath, xmlfilebase ) local xhtmlfilename = joinfile(basepath, xhtmlfilebase ) local htmlfilename = joinfile(basepath, htmlfilebase ) local specificationfilename = joinfile(basepath, specificationfilebase) -- local defaultfilebase = addsuffix(basename .. "-defaults", "css") local imagefilebase = addsuffix(basename .. "-images", "css") local stylefilebase = addsuffix(basename .. "-styles", "css") local templatefilebase = addsuffix(basename .. "-templates","css") -- local defaultfilename = joinfile(stylepath,defaultfilebase ) local imagefilename = joinfile(stylepath,imagefilebase ) local stylefilename = joinfile(stylepath,stylefilebase ) local templatefilename = joinfile(stylepath,templatefilebase) local cssfile = finetuning.cssfile -- we keep track of all used files local files = { } -- we always load the defaults and optionally extra css files; we also copy the example -- css file so that we always have the latest version local cssfiles = { defaultfilebase, imagefilebase, stylefilebase, } local examplefilename = resolvers.find_file("export-example.css") if examplefilename then local data = io.loaddata(examplefilename) if not data or data == "" then data = "/* missing css file */" elseif not usecssnamespace then data = gsub(data,cssnamespace,"") end io.savedata(defaultfilename,data) end if cssfile then local list = table.unique(settings_to_array(cssfile)) for i=1,#list do local source = addsuffix(list[i],"css") local target = joinfile(stylepath,file.basename(source)) cssfiles[#cssfiles+1] = source if not lfs.isfile(source) then source = joinfile("../",source) end if lfs.isfile(source) then report_export("copying %s",source) file.copy(source,target) end end end local x_styles, h_styles = allusedstylesheets(cssfiles,files,"styles") -- at this point we're ready for the content; the collector also does some -- housekeeping and data collecting; at this point we still have an xml -- representation that uses verbose element names and carries information in -- attributes local data = tree.data for i=1,#data do if data[i].tg ~= "document" then data[i] = { } end end local result, embedded = allcontent(tree,embedmath) -- embedfile is for testing local attach = backends.nodeinjections.attachfile if embedfile and attach then -- only for testing attach { data = concat{ wholepreamble(true), result }, name = file.basename(xmlfilename), registered = "export", title = "raw xml export", method = v_hidden, mimetype = "application/mathml+xml", } end -- if embedmath and attach then -- local refs = { } -- for k, v in sortedhash(embedded) do -- attach { -- data = v, -- file = file.basename(k), -- name = file.addsuffix(k,"xml"), -- registered = k, -- reference = k, -- title = "xml export snippet: " .. k, -- method = v_hidden, -- mimetype = "application/mathml+xml", -- } -- refs[k] = 0 -- end -- end result = concat { wholepreamble(true), x_styles, -- adds to files result, } cssfiles = table.unique(cssfiles) -- we're now ready for saving the result in the xml file report_export("saving xml data in %a",xmlfilename) io.savedata(xmlfilename,result) report_export("saving css image definitions in %a",imagefilename) io.savedata(imagefilename,wrapups.allusedimages(basename)) report_export("saving css style definitions in %a",stylefilename) io.savedata(stylefilename,wrapups.allusedstyles(basename)) report_export("saving css template in %a",templatefilename) io.savedata(templatefilename,allusedelements(basename)) -- additionally we save an xhtml file; for that we load the file as xml tree report_export("saving xhtml variant in %a",xhtmlfilename) local xmltree = cleanxhtmltree(xml.convert(result)) xml.save(xmltree,xhtmlfilename) -- now we save a specification file that can b eused for generating an epub file -- looking at identity is somewhat redundant as we also inherit from interaction -- at the tex end local identity = interactions.general.getidentity() local specification = { name = file.removesuffix(v), identifier = os.uuid(), images = wrapups.uniqueusedimages(), imagefile = joinfile("styles",imagefilebase), imagepath = "images", stylepath = "styles", xmlfiles = { xmlfilebase }, xhtmlfiles = { xhtmlfilebase }, htmlfiles = { htmlfilebase }, styles = cssfiles, htmlroot = htmlfilebase, language = languagenames[texgetcount("mainlanguagenumber")], title = validstring(finetuning.title) or validstring(identity.title), subtitle = validstring(finetuning.subtitle) or validstring(identity.subtitle), author = validstring(finetuning.author) or validstring(identity.author), firstpage = validstring(finetuning.firstpage), lastpage = validstring(finetuning.lastpage), } report_export("saving specification in %a",specificationfilename,specificationfilename) io.savedata(specificationfilename,table.serialize(specification,true)) -- the html export for epub is different in the sense that it uses div's instead of -- specific tags report_export("saving div based alternative in %a",htmlfilename) remap(specification,xmltree) local title = specification.title if not title or title == "" then title = "no title" -- believe it or not, but a <title/> can prevent viewing in browsers end local variables = { style = h_styles, body = xml.tostring(xml.first(xmltree,"/div")), preamble = wholepreamble(false), title = title, } io.savedata(htmlfilename,replacetemplate(htmltemplate,variables,"xml")) -- finally we report how an epub file can be made (using the specification) report_export("") report_export('create epub with: mtxrun --script epub --make "%s" [--purge --rename --svgmath]',file.nameonly(basename)) report_export("") stoptiming(treehash) end local appendaction = nodes.tasks.appendaction local enableaction = nodes.tasks.enableaction function structurestags.setupexport(t) merge(finetuning,t) keephyphens = finetuning.hyphen == v_yes exportproperties = finetuning.properties if exportproperties == v_no then exportproperties = false end end local function startexport(v) if v and not exporting then report_export("enabling export to xml") -- not yet known in task-ini appendaction("shipouts","normalizers", "nodes.handlers.export") -- enableaction("shipouts","nodes.handlers.export") enableaction("shipouts","nodes.handlers.accessibility") enableaction("math", "noads.handlers.tags") -- appendaction("finalizers","lists","builders.paragraphs.tag") -- enableaction("finalizers","builders.paragraphs.tag") luatex.registerstopactions(structurestags.finishexport) exporting = v end end function structurestags.finishexport() if exporting then stopexport(exporting) exporting = false end end directives.register("backend.export",startexport) -- maybe .name statistics.register("xml exporting time", function() if exporting then return string.format("%s seconds, version %s", statistics.elapsedtime(treehash),exportversion) end end) end -- These are called at the tex end: implement { name = "setupexport", actions = structurestags.setupexport, arguments = { { { "align" }, { "bodyfont", "dimen" }, { "width", "dimen" }, { "properties" }, { "hyphen" }, { "title" }, { "subtitle" }, { "author" }, { "firstpage" }, { "lastpage" }, { "svgstyle" }, { "cssfile" }, } } } implement { name = "finishexport", actions = structurestags.finishexport, } implement { name = "settagitemgroup", actions = structurestags.setitemgroup, arguments = { "boolean", "integer", "string" } } implement { name = "settagitem", actions = structurestags.setitem, arguments = "string" } implement { name = "settagdelimitedsymbol", actions = structurestags.settagdelimitedsymbol, arguments = "string" } implement { name = "settagsubsentencesymbol", actions = structurestags.settagsubsentencesymbol, arguments = "string" } implement { name = "settagsynonym", actions = structurestags.setsynonym, arguments = "string" } implement { name = "settagsorting", actions = structurestags.setsorting, arguments = "string" } implement { name = "settagnotation", actions = structurestags.setnotation, arguments = { "string", "integer" } } implement { name = "settagnotationsymbol", actions = structurestags.setnotationsymbol, arguments = { "string", "integer" } } implement { name = "settaghighlight", actions = structurestags.sethighlight, arguments = { "string", "integer" } } implement { name = "settagfigure", actions = structurestags.setfigure, arguments = { "string", "string", "string", "dimen", "dimen", "string" } } implement { name = "settagcombination", actions = structurestags.setcombination, arguments = { "integer", "integer" } } implement { name = "settagtablecell", actions = structurestags.settablecell, arguments = { "integer", "integer", "integer" } } implement { name = "settagtabulatecell", actions = structurestags.settabulatecell, arguments = "integer" } implement { name = "settagregister", actions = structurestags.setregister, arguments = { "string", "integer" } } implement { name = "settaglist", actions = structurestags.setlist, arguments = "integer" }
-- Copyright (c) 2021 Kirazy -- Part of Artisanal Reskins: Bob's Mods -- -- See LICENSE in the project directory for license information. -- Check to see if reskinning needs to be done. if not (reskins.bobs and reskins.bobs.triggers.assembly.entities) then return end -- Flag available for Mini-Machines compatibility pass if reskins.compatibility then reskins.compatibility.triggers.minimachines.electrolysers = true end -- Set input parameters local inputs = { type = "assembling-machine", icon_name = "electrolyser", base_entity = "chemical-plant", mod = "bobs", group = "assembly", particles = {["big"] = 1, ["medium"] = 2}, make_remnants = false, } local tier_map = { ["electrolyser"] = {1, 1}, ["electrolyser-2"] = {2, 2}, ["electrolyser-3"] = {3, 3}, ["electrolyser-4"] = {4, 3}, ["electrolyser-5"] = {5, 5} } -- Reskin entities, create and assign extra details for name, map in pairs(tier_map) do -- Fetch entity local entity = data.raw[inputs.type][name] -- Check if entity exists, if not, skip this iteration if not entity then goto continue end -- Parse map local tier = map[1] local shadow = map[2] -- Determine what tint we're using inputs.tint = reskins.lib.tint_index[tier] -- Handle unique icons inputs.icon_base = "electrolyser-"..tier inputs.icon_mask = inputs.icon_base inputs.icon_highlights = inputs.icon_base reskins.lib.setup_standard_entity(name, tier, inputs) -- Reskin entities entity.animation = reskins.lib.make_4way_animation_from_spritesheet({ layers = { -- Base { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/electrolyser-"..tier.."-base.png", width = 136, height = 130, frame_count = 1, shift = util.by_pixel(17, 0), hr_version = { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/hr-electrolyser-"..tier.."-base.png", width = 272, height = 260, frame_count = 1, shift = util.by_pixel(17, 0), scale = 0.5 } }, -- Mask { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/electrolyser-"..tier.."-mask.png", width = 136, height = 130, frame_count = 1, shift = util.by_pixel(17, 0), tint = inputs.tint, hr_version = { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/hr-electrolyser-"..tier.."-mask.png", width = 272, height = 260, frame_count = 1, shift = util.by_pixel(17, 0), tint = inputs.tint, scale = 0.5 } }, -- Highlights { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/electrolyser-"..tier.."-highlights.png", width = 136, height = 130, frame_count = 1, shift = util.by_pixel(17, 0), blend_mode = reskins.lib.blend_mode, -- "additive", hr_version = { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/hr-electrolyser-"..tier.."-highlights.png", width = 272, height = 260, frame_count = 1, shift = util.by_pixel(17, 0), blend_mode = reskins.lib.blend_mode, -- "additive", scale = 0.5 } }, -- Shadow { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/electrolyser-"..shadow.."-shadow.png", width = 136, height = 130, frame_count = 1, shift = util.by_pixel(17, 0), draw_as_shadow = true, hr_version = { filename = reskins.bobs.directory.."/graphics/entity/assembly/electrolyser/hr-electrolyser-"..shadow.."-shadow.png", width = 272, height = 260, frame_count = 1, shift = util.by_pixel(17, 0), draw_as_shadow = true, scale = 0.5 } } } }) entity.water_reflection = util.copy(data.raw["storage-tank"]["storage-tank"].water_reflection) -- Label to skip to next iteration ::continue:: end
local maxId = 0 local fprpVars = {} local fprpVarById = {} -- the amount of bits assigned to the value that determines which fprpVar we're sending/receiving local fprp_ID_BITS = 8 local UNKNOWN_fprpVAR = 255 -- Should be equal to 2^fprp_ID_BITS - 1 fprp.fprp_ID_BITS = fprp_ID_BITS function fprp.registerfprpVar(name, writeFn, readFn) maxId = maxId + 1 -- UNKNOWN_fprpVAR is reserved for unknown values if maxId >= UNKNOWN_fprpVAR then fprp.error(string.format("Too many fprpVar registrations! fprpVar '%s' triggered this error", name), 2) end fprpVars[name] = {id = maxId, name = name, writeFn = writeFn, readFn = readFn} fprpVarById[maxId] = fprpVars[name] end -- Unknown values have unknown types and unknown identifiers, so this is sent inefficiently local function writeUnknown(name, value) net.WriteUInt(UNKNOWN_fprpVAR, 8); net.WriteString(name); net.WriteType(value); end -- Read the value of a fprpVar that was not registered local function readUnknown() return net.ReadString(), net.ReadType(net.ReadUInt(8)); end local warningsShown = {} local function warnRegistration(name) if warningsShown[name] then return end warningsShown[name] = true ErrorNoHalt(string.format([[Warning! fprpVar '%s' wasn't registered! Please contact the author of the fprp Addon to fix this. Until this is fixed you don't need to worry about anything. Everything will keep working. It's just that registering fprpVars would make fprp faster.]], name)); debug.Trace(); end function fprp.writeNetfprpVar(name, value) local fprpVar = fprpVars[name] if not fprpVar then warnRegistration(name); return writeUnknown(name, value); end net.WriteUInt(fprpVar.id, fprp_ID_BITS); return fprpVar.writeFn(value); end function fprp.writeNetfprpVarRemoval(name) local fprpVar = fprpVars[name] if not fprpVar then warnRegistration(name); net.WriteUInt(UNKNOWN_fprpVAR, 8); net.WriteString(name); return end net.WriteUInt(fprpVar.id, fprp_ID_BITS); end function fprp.readNetfprpVar() local fprpVarId = net.ReadUInt(fprp_ID_BITS); local fprpVar = fprpVarById[fprpVarId] if fprpVarId == UNKNOWN_fprpVAR then local name, value = readUnknown(); return name, value end local val = fprpVar.readFn(value); return fprpVar.name, val end function fprp.readNetfprpVarRemoval() local id = net.ReadUInt(fprp_ID_BITS); return id == 255 and net.ReadString() or fprpVarById[id].name end -- The shekel is a double because it accepts higher values than Int and UInt, which are undefined for >32 bits fprp.registerfprpVar("shekel", net.WriteDouble, net.ReadDouble); fprp.registerfprpVar("salary", fp{fn.Flip(net.WriteInt), 32}, fp{net.ReadInt, 32}); fprp.registerfprpVar("rpname", net.WriteString, net.ReadString); fprp.registerfprpVar("job", net.WriteString, net.ReadString); fprp.registerfprpVar("HasGunlicense", net.WriteBit, fc{tobool, net.ReadBit}); fprp.registerfprpVar("Arrested", net.WriteBit, fc{tobool, net.ReadBit}); fprp.registerfprpVar("wanted", net.WriteBit, fc{tobool, net.ReadBit}); fprp.registerfprpVar("wantedReason", net.WriteString, net.ReadString); fprp.registerfprpVar("agenda", net.WriteString, net.ReadString);
local S = pulse_network.S function pulse_network.add_storage_cell(id, texture, desc, add_types, add_items) minetest.register_node(id, { stack_max = 16, tiles = texture, sounds = trinium.sounds.default_metal, description = desc, groups = {cracky = 1, pulsenet_slave = 1}, on_pulsenet_connection = function(_, ctrlpos) local meta = minetest.get_meta(ctrlpos) local cs = meta:get_int"capacity_types" local items = meta:get_int"capacity_items" meta:set_int("capacity_types", cs + add_types) meta:set_int("capacity_items", items + add_items) end, can_dig = function(pos) local meta = minetest.get_meta(pos) if meta:get_int"network_destruction" == 1 then return true end local ctrlpos = minetest.deserialize(meta:get_string"controller_pos") if not ctrlpos or minetest.get_node(ctrlpos).name ~= "pulse_network:controller" then return true end local ctrl_meta = minetest.get_meta(ctrlpos) return ctrl_meta:get_int"capacity_types" - add_types >= ctrl_meta:get_int"used_types" and ctrl_meta:get_int"capacity_items" - add_items >= ctrl_meta:get_int"used_items" end, after_dig_node = function(_, _, oldmetadata) local ctrlpos = oldmetadata.fields.controller_pos if not ctrlpos then return end ctrlpos = ctrlpos:data() if not ctrlpos then return end if ctrlpos and minetest.get_node(ctrlpos).name == "pulse_network:controller" then local ctrl_meta = minetest.get_meta(ctrlpos) local cs = ctrl_meta:get_int"capacity_types" local items = ctrl_meta:get_int"capacity_items" ctrl_meta:set_int("capacity_types", cs - add_types) ctrl_meta:set_int("capacity_items", items - add_items) pulse_network.trigger_update(ctrlpos) end end, }) end -- per tier, type amount is divided by 3, and storage is multiplied by 8 pulse_network.add_storage_cell("pulse_network:storage_cell", {"pulse_network.storage_cell.png"}, S"Pulse Network Storage Cell", 27, 5000) pulse_network.add_storage_cell("pulse_network:void_storage_cell", {"pulse_network.void_storage_cell.png"}, S"Void Pulse Network Storage Cell", 9, 40000) pulse_network.add_storage_cell("pulse_network:condensed_storage_cell", {"pulse_network.condensed_storage_cell.png"}, S"Condensed Pulse Network Storage Cell", 3, 320000) pulse_network.add_storage_cell("pulse_network:super_storage_cell", {"pulse_network.super_storage_cell.png"}, S"Ultimate Pulse Network Storage Cell", 1, 2560000)
object_mobile_dressed_tatooine_icon_tosche = object_mobile_shared_dressed_tatooine_icon_tosche:new { } ObjectTemplates:addTemplate(object_mobile_dressed_tatooine_icon_tosche, "object/mobile/dressed_tatooine_icon_tosche.iff")
CheatCoreCM = CheatCoreCM or {} local modVehicles = {} -- do not modify --correct format is: modVehicles["MODID"] = { {"display name (can be anything)", "vehicle ID", "category name (can be anything)"} } --table key must be the modID defined in the mod's modinfo.txt file, i.e modVehicles["FRUsedCars"] for Filibuster Rhyme's used cars. --definitions go below here. thank you Oh God Spiders No for the existing definitions modVehicles["VileM113APC"] = { {"M113A1","Base.m113a1", "Vile M113APC"}, } modVehicles["FRUsedCars"] = { {"Roanoke Goat", "Base.65gto", "Filibuster"}, {"Chevalier El Chimera", "Base.68elcamino", "Filibuster"}, {"Utana Lynx", "Base.68wildcat", "Filibuster"}, {"Utana Lynx", "Base.68wildcatconvert", "Filibuster"}, {"Dash Blitzer", "Base.69charger", "Filibuster"}, {"Dash Blitzer R/P Edition", "Base.69chargerdaytona", "Filibuster"}, {"Chevalier Bulette", "Base.70chevelle", "Filibuster"}, {"Chevalier El Chimera", "Base.70elcamino", "Filibuster"}, {"Chevalier Nyala", "Base.71impala", "Filibuster"}, {"Franklin Thundercougar", "Base.73falcon", "Filibuster"}, {"Franklin Jalapeno", "Base.73pinto", "Filibuster"}, {"Roanoke Grand Slam", "Base.77transam", "Filibuster"}, {"Laumet Davis Hogg", "Base.79brougham", "Filibuster"}, {"Franklin Crest Andarta LTD", "Base.85vicranger", "Filibuster"}, {"Franklin Crest Andarta LTD", "Base.85vicsed", "Filibuster"}, {"Franklin Crest Andarta LTD", "Base.85vicsheriff", "Filibuster"}, {"Franklin Crest Andarta Wagon", "Base.85vicwag", "Filibuster"}, {"Franklin Crest Andarta Wagon", "Base.85vicwag2", "Filibuster"}, {"Franklin Trip", "Base.86bounder", "Filibuster"}, {"Slavski Nogo", "Base.86yugo", "Filibuster"}, {"Chevalier Kobold", "Base.87blazer", "Filibuster"}, {"Chevalier D20", "Base.87c10fire", "Filibuster"}, {"Chevalier D20", "Base.87c10lb", "Filibuster"}, {"Chevalier D20", "Base.87c10mccoy", "Filibuster"}, {"Chevalier D20", "Base.87c10sb", "Filibuster"}, {"Chevalier D20", "Base.87c10utility", "Filibuster"}, {"Chevalier Carnifex", "Base.87suburban", "Filibuster"}, {"Dash Buck", "Base.90ramlb", "Filibuster"}, {"Dash Buck", "Base.90ramsb", "Filibuster"}, {"Chevalier Kobold", "Base.91blazerpd", "Filibuster"}, {"Tokai Renaissance", "Base.91crx", "Filibuster"}, {"Chevalier Cosmo", "Base.astrovan", "Filibuster"}, {"Franklin EF70 Box Truck", "Base.f700box", "Filibuster"}, {"Franklin EF70 Dump Truck", "Base.f700dump", "Filibuster"}, {"Franklin EF70 Flatbed", "Base.f700flatbed", "Filibuster"}, {"Fire Engine", "Base.firepumper", "Filibuster"}, {"The General Lee", "Base.generallee", "Filibuster"}, {"The General Meh", "Base.generalmeh", "Filibuster"}, {"M1025", "Base.hmmwvht", "Filibuster"}, {"M1069", "Base.hmmwvtr", "Filibuster"}, {"Pazuzu N5", "Base.isuzubox", "Filibuster"}, {"Pazuzu N5", "Base.isuzuboxelec", "Filibuster"}, {"Pazuzu N5", "Base.isuzuboxfood", "Filibuster"}, {"Pazuzu N5", "Base.isuzuboxmccoy", "Filibuster"}, {"M151A2", "Base.m151canvas", "Filibuster"}, {"M35A2", "Base.m35a2bed", "Filibuster"}, {"M35A2", "Base.m35a2covered", "Filibuster"}, {"Move Urself Box Truck", "Base.moveurself", "Filibuster"}, {"Pursuit Special", "Base.pursuitspecial", "Filibuster"}, {"Franklin BE70 School Bus", "Base.schoolbus", "Filibuster"}, {"Franklin BE70 School Bus", "Base.schoolbusshort", "Filibuster"}, {"Bohag 244", "Base.volvo244", "Filibuster"}, } modVehicles["FRUsedCarsBETA"] = modVehicles["FRUsedCars"] modVehicles["ZIL130PACK2"] = { {"ZIL-130","Base.zil130", "ZIL-130 #2"}, {"AC-40(130)","Base.ac40", "ZIL-130 #2"}, {"ZIL-130 Bread Furgon","Base.zil130bread", "ZIL-130 #2"}, {"ZIL-130","Base.zil130tent", "ZIL-130 #2"}, {"ZIL-MMZ-555","Base.zil130mmz555", "ZIL-130 #2"}, {"ZIL-130 Milk Furgon","Base.zil130milk", "ZIL-130 #2"}, {"ZIL-130 Furgon","Base.zil130furgon", "ZIL-130 #2"}, {"ZIL-130G","Base.zil130g", "ZIL-130 #2"}, {"ZIL-130G","Base.zil130gtent", "ZIL-130 #2"}, {"ZIL-130 Food Furgon","Base.zil130products", "ZIL-130 #2"}, } modVehicles["MysteryMachineOGSN"] = { {"Mystery Machine","Base.VanMysterymachine", "Mystery Machine"}, } CheatCoreCM.modVehicles = modVehicles -- do not modify. do not place definitions below this
local date = require("../init") local deepEqual = require("deep-equal") require("tap")(function(test) test("date-strptime-simple-date", function() local str = "Jan 01 1970" local pos, got = date.strptime(str, "%b %d %Y") local expected = { year = 1970, month = 1, day = 1, hour = 0, min = 0, sec = 0, wday = 5, yday = 1, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-simple-time", function() local str = "01:02:03" local pos, got = date.strptime(str, "%T") local expected = { year = 1900, month = 1, day = 0, hour = 1, min = 2, sec = 3, wday = 1, yday = 1, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-simple-timezone", function() local str = "+0100" local pos, got = date.strptime(str, "%z") local expected = { year = 1900, month = 1, day = 0, hour = 0, min = 0, sec = 0, wday = 1, yday = 1, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-complete", function() local str = "Fri Nov 20 15:18:40 -0130 2015" local pos, got = date.strptime(str, "%a %b %d %T %z %Y") local expected = { year = 2015, month = 11, day = 20, hour = 15, min = 18, sec = 40, wday = 6, yday = 324, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-iso-8601", function() local str = "2015-12-03T20:32:29.441862132+0000" local pos, got = date.strptime(str, "%Y-%m-%dT%H:%M:%S.%N%z") local expected = { year = 2015, month = 12, day = 03, hour = 20, min = 32, sec = 29, wday = 5, yday = 337, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-iso-8601-broken-front", function() local str = "2015-12-0320:32:29.441862132+0000" local pos, got = date.strptime(str, "%Y-%m-%dT%H:%M:%S.%N%z") assert(deepEqual(0, pos)) assert(deepEqual(nil, got)) end) test("date-strptime-iso-8601-broken-back", function() local str = "2015-12-03T20:32:29.441862132%0000" local pos, got = date.strptime(str, "%Y-%m-%dT%H:%M:%S.%N%z") assert(deepEqual(0, pos)) assert(deepEqual(nil, got)) end) test("date-strptime-with-garbage-at-end", function() local str, garbage = "Fri Nov 20 15:18:40 -0130 2015", "Lots of garbage" local pos, got = date.strptime(str .. garbage, "%a %b %d %T %z %Y") local expected = { year = 2015, month = 11, day = 20, hour = 15, min = 18, sec = 40, wday = 6, yday = 324, isdst = false, } assert(deepEqual(#str, pos)) assert(deepEqual(expected, got)) end) test("date-strptime-with-garbage-at-beginning", function() local str, garbage = "Fri Nov 20 15:18:40 -0130 2015", "Lots of garbage" local pos, got = date.strptime(garbage .. str, "%a %b %d %T %z %Y") assert(deepEqual(0, pos)) assert(deepEqual(nil, got)) end) test("date-strptime-broken-format", function() local str = "Fri Nov 20 15:18:40 -0130 2015" local pos, got = date.strptime(str, "%a %b %$") assert(deepEqual(0, pos)) assert(deepEqual(nil, got)) end) test("date-strptime-empty-string", function() local pos, got = date.strptime("", "%a %b %d %T %z %Y") assert(deepEqual(0, pos)) assert(deepEqual(nil, got)) end) end)
--- --- 控制空闲时是否允许屏幕睡眠 --- Created by sugood(https://github.com/sugood). --- DateTime: 2020/10/24 14:13 --- local menuBarItem = nil local setCaffeine= function() if config ~=nil and config[1].caffeine == 'on' and menuBarItem == nil then print("设置状态栏") menuBarItem= hs.menubar.new() menuBarItem:setTitle("") menuBarItem:setIcon("~/.hammerspoon/icon/caffeine-on.pdf") hs.caffeinate.set("displayIdle", true) else hs.caffeinate.set("displayIdle", false) end end function resetCaffeineMeun() if(config ~=nil and config[1].caffeine == 'on' and menuBarItem:isInMenuBar() == false) then print("重置状态栏") menuBarItem:delete() menuBarItem= hs.menubar.new() menuBarItem:setTitle("") menuBarItem:setIcon("~/.hammerspoon/icon/caffeine-on.pdf") --hs.caffeinate.set("displayIdle", true) end end function initData() setCaffeine() --监听咖啡因的状态,判断是否要重置 hs.timer.doEvery(1, resetCaffeineMeun) end -- 初始化 initData()
local alias = minetest.register_alias -- Remove duplicated items from the carbone subgame because of Moreores mod -- Stone alias("default:stone_with_tin", "default:stone") alias("default:stone_with_silver", "default:stone") -- Lump alias("default:tin_lump", "default:stone") alias("default:silver_lump", "default:stone") -- Ingot alias("default:tin_ingot", "default:stone") alias("default:silver_ingot", "default:stone") -- Block alias("default:tinblock", "default:stone") alias("default:silverblock", "default:stone") -- Tools alias("default:pick_silver", "default:stone") alias("default:shovel_silver", "default:stone") alias("default:axe_silver", "default:stone") alias("default:sword_silver", "default:stone") alias("default:knife_silver", "default:stone") -- Remove torch from torches => remise des torches par défaut alias("torches:floor", "default:torch") alias("torches:wand", "default:torch") -- Remove copper_rail from moreores => utilisation des rail_copper du mod carts alias("moreores:copper_rail", "carts:rail_copper") -- Old fishing mod to the new fishing mod alias("fishing:fish_cooked", "fishing:fish") alias("fishing:worm", "fishing:bait_worm") -- Old itemframes mod to the new itemframes(v2) mod alias("itemframes:pedestal", "itemframes:pedestal_cobble") -- Remove "moreores:copper_rail" for "carts:copper_rail" alias("moreores:copper_rail", "carts:rail_copper") -- Remove "multitest:hayblock" because farming redo include it now alias("multitest:hayblock", "farming:straw") -- Remove "darkage:stair_straw", "darkage:straw", "darkage:straw_bale" and "darkage:adobe" alias("darkage:stair_straw", "farming:straw") alias("darkage:straw", "farming:straw") alias("darkage:straw_bale", "farming:straw") alias("darkage:adobe", "farming:straw") -- Remove "wiki:wiki" alias("wiki:wiki", "default:bookshelf") -- Remove "building_blocks:knife" alias("building_blocks:knife", "default:sword_steel") -- Remove "xmas_tree" from snow mod alias("snow:xmas_tree", "default:dirt") -- remove "fake_fire:flint_and_steel" from homedecor_modpack mod alias("fake_fire:flint_and_steel", "fire:flint_and_steel") -- remove ongen pine saplings from moretrees alias("moretrees:pine_sapling_ongen", "default:pine_sapling") -- Remove bedrock mod alias("bedrock:bedrock", "default:cobble")
local PAIStrings = { -- ================================================================================================================= -- Language specific texts that need to be translated -- -- ================================================================================================================= -- == MENU/PANEL TEXTS == -- -- ----------------------------------------------------------------------------------------------------------------- -- PAIntegration Menu -- SI_PA_MENU_INTEGRATION_DESCRIPTION = "PAIntegration peut faire fonctionner PersonalAssistant avec d'autres add-ons tels que Dolgubon's Lazy Writ Crafter ou FCO ItemSaver", SI_PA_MENU_INTEGRATION_NOTHING_AVAILABLE = "Aucun add-on supporté par PAIntegration n'a été détecté.", -- Dolgubon's Lazy Writ Crafter -- SI_PA_MENU_INTEGRATION_LWC_COMPATIBILITY = "Compatibilité avec Dolgubon's Lazy Writ Crafter", SI_PA_MENU_INTEGRATION_LWC_COMPATIBILITY_T = "Si vous avez des commandes d'artisanat en cours et que 'Prendre les matériaux de commande' est activé dans Dolgubon's Lazy Writ Crafter, alors ces objets ne seront pas déposés même si vous avez choisi 'Déposer en banque'. Ceci est pour éviter de remettre directement en banque les objets qui viennent d'être retirés.", -- FCO ItemSaver -- SI_PA_MENU_INTEGRATION_FCOIS_LOCKED_PREVENT_SELLING = "Empêcher la vente auto. des objets verrouillés", --SI_PA_MENU_INTEGRATION_FCOIS_LOCKED_PREVENT_MOVING = "", --SI_PA_MENU_INTEGRATION_FCOIS_LOCKED_PREVENT_MOVING_T = "", SI_PA_MENU_INTEGRATION_FCOIS_SELL_AUTOSELL_MARKED = "Vente/Recel auto. des marqués aux marchands", --SI_PA_MENU_INTEGRATION_FCOIS_ITEM_MOVE_MARKED = "", -- ================================================================================================================= -- == CHAT OUTPUTS == -- -- ----------------------------------------------------------------------------------------------------------------- -- PAIntegration -- -- ================================================================================================================= -- == OTHER STRINGS FOR MENU == -- -- ----------------------------------------------------------------------------------------------------------------- -- PAIntegration Menu -- --SI_PA_MENU_INTEGRATION_PAB_REQUIRED = "", --SI_PA_MENU_INTEGRATION_PAJ_REQUIRED = "", SI_PA_MENU_INTEGRATION_MORE_TO_COME = "D'autres options d'intégration pour FCO ItemSaver seront ajoutées dans de futures mises à jour.", } for key, value in pairs(PAIStrings) do SafeAddString(_G[key], value, 1) end
-- A small game to learn LUA and some game dev function love.load() -- Init basics love.window.setTitle("Eliberate Us") love.window.setIcon( love.image.newImageData("assets/img/player.png") ) bg = love.graphics.newImage("assets/img/background.png") introbg = love.graphics.newImage("assets/img/intro.png") outrobg = love.graphics.newImage("assets/img/outro.png") introSound = love.audio.newSource("assets/sound/intro.mp3") outroSound = love.audio.newSource("assets/sound/outro.mp3") pausedbg = love.graphics.newImage("assets/img/paused.png") -- Init Important Vars isIntro = true isPaused = false isGame = false -- Init Vars isFullScreen = false eclipse = love.graphics.newImage("assets/img/eclipse.jpg") sun = love.graphics.newImage("assets/img/sun.jpg") player = love.graphics.newImage("assets/img/player.png") mapSize = 6 tiles = {} tileSize = 80 playerSize = 20 playerPos = { ["xpos"] = playerSize, ["ypos"] = playerSize, ax = playerSize, ay = playerSize} speed = 10 i = 0 xpos = 0 ypos = -tileSize badTilesCount = 0 goodTilesCount = 0 introAudioPlayed = false outroAudioPlayed = false timePassed = 0 -- Resize window based on tiles windowSize = mapSize * tileSize love.window.setMode( windowSize + 80, windowSize ) -- Intro audio play once time = love.timer.getTime() endTime = love.timer.getTime() otime = love.timer.getTime() oendTime = love.timer.getTime() while (i < (mapSize * mapSize)) do if (i % mapSize) == 0 then xpos = 0 ypos = ypos + tileSize else xpos = xpos + tileSize end badTile = math.ceil(math.random() * 10 ) % math.ceil(math.random() * 10) == 0 local tile = {} tile["xpos"] = xpos tile["ypos"] = ypos tile["bad"] = badTile if (badTile) then badTilesCount = badTilesCount + 1 else goodTilesCount = goodTilesCount + 1 end tiles[i] = tile i = i + 1 end end function posTextString(stra, y) l = string.len(stra) love.graphics.print(stra, windowSize + 10 , y) end function love.draw() if isGame then love.graphics.draw(bg, 0 , 0) for k, v in pairs(tiles) do if tiles[k]["bad"] == true then love.graphics.draw(eclipse, tiles[k]["xpos"], tiles[k]["ypos"]) else love.graphics.draw(sun, tiles[k]["xpos"], tiles[k]["ypos"]) end end love.graphics.draw(player, playerPos.ax, playerPos.ay) -- Draw statistics posTextString("Statistics:", 10) posTextString("Bad: " .. badTilesCount, 30) posTextString("Good: " .. goodTilesCount, 50) posTextString("Elapsed:\n" .. timePassed, 70) --posTextString("Elapsed:\n" .. os.date("%c", os.time()), 110) -- Copyright posTextString("Author \nZenger", windowSize - 60) timePassed = timePassed + 1 end if isPaused then scaleRatioX = (windowSize + 80) / pausedbg:getWidth() scaleRatioY = windowSize / pausedbg:getHeight() love.graphics.draw(pausedbg, 0, 0, 0, scaleRatioX, scaleRatioY ) end if isIntro then scaleRatioX = (windowSize + 80) / introbg:getWidth() scaleRatioY = windowSize / introbg:getHeight() love.graphics.draw(introbg, 0 , 0, 0, scaleRatioX, scaleRatioY) if not introAudioPlayed then introSound:play() end endTime = love.timer.getTime() if math.floor( endTime - time ) == 12 then introAudioPlayed = true end end if isOutro then scaleRatioX = (windowSize + 80) / outrobg:getWidth() scaleRatioY = windowSize / outrobg:getHeight() love.graphics.draw(outrobg, 0 , 0, 0, scaleRatioX, scaleRatioY) isGame = false oendTime = love.timer.getTime() if not outroAudioPlayed then outroSound:play() end print(oendTime - otime) if math.floor( oendTime - otime ) == 4 then outroAudioPlayed = true end end end function switchTile() x = playerPos["xpos"] - playerSize y = playerPos["ypos"] - playerSize for k,v in pairs(tiles) do if (tiles[k]["xpos"] == x and tiles[k]["ypos"] == y) then if tiles[k]["bad"] then tiles[k]["bad"] = false badTilesCount = badTilesCount - 1 else tiles[k]["bad"] = true badTilesCount = badTilesCount + 1 end end end end function love.keypressed(key) if key == "escape" then isPaused = not isPaused if isPaused then isGame = false else isGame = true end --love.event.quit() end local max = (mapSize * tileSize) - tileSize if (key == "right" or key == "d") and (playerPos["xpos"] < max) then playerPos["xpos"] = playerPos["xpos"] + tileSize switchTile() end if (key == "left" or key == "a") and (playerPos["xpos"] ~= playerSize) then playerPos["xpos"] = playerPos["xpos"] - tileSize switchTile() end if (key == "up" or key == "w") and (playerPos["ypos"] ~= playerSize) then playerPos["ypos"] = playerPos["ypos"] - tileSize switchTile() end if (key == "down" or key == "s") and (playerPos["ypos"] < max) then playerPos["ypos"] = playerPos["ypos"] + tileSize switchTile() end if (badTilesCount == 0) then isOutro = true otime = love.timer.getTime() end if key == " " then isIntro = false isGame = true introAudioPlayed = true introSound:stop() end if key == "q" then love.event.quit() end end function love.update(dt) playerPos.ax = playerPos.ax - ((playerPos.ax - playerPos["xpos"]) * speed * dt) playerPos.ay = playerPos.ay - ((playerPos.ay - playerPos["ypos"]) * speed * dt) end
Key = { -- LBUTTON = 0x01, -- RBUTTON = 0x02, CANCEL = 0x03, -- MBUTTON = 0x04, -- XBUTTON1 = 0x05, -- XBUTTON2 = 0x06, BACK = 0x08, TAB = 0x09, CLEAR = 0x0c, RETURN = 0x0d, SHIFT = 0x10, CONTROL = 0x11, MENU = 0x12, PAUSE = 0x13, CAPITAL = 0x14, KANA = 0x15, HANGEUL = 0x15, HANGUL = 0x15, JUNJA = 0x17, FINAL = 0x18, HANJA = 0x19, KANJI = 0x19, ESCAPE = 0x1b, CONVERT = 0x1c, NONCONVERT = 0x1d, ACCEPT = 0x1e, MODECHANGE = 0x1f, SPACE = 0x20, PRIOR = 0x21, NEXT = 0x22, END = 0x23, HOME = 0x24, LEFT = 0x25, UP = 0x26, RIGHT = 0x27, DOWN = 0x28, SELECT = 0x29, PRINT = 0x2a, EXECUTE = 0x2b, SNAPSHOT = 0x2c, INSERT = 0x2d, DELETE = 0x2e, HELP = 0x2f, DIGIT_0 = 0x30, DIGIT_1 = 0x31, DIGIT_2 = 0x32, DIGIT_3 = 0x33, DIGIT_4 = 0x34, DIGIT_5 = 0x35, DIGIT_6 = 0x36, DIGIT_7 = 0x37, DIGIT_8 = 0x38, DIGIT_9 = 0x39, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4a, K = 0x4b, L = 0x4c, M = 0x4d, N = 0x4e, O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, LWIN = 0x5b, RWIN = 0x5c, APPS = 0x5d, SLEEP = 0x5f, NUMPAD0 = 0x60, NUMPAD1 = 0x61, NUMPAD2 = 0x62, NUMPAD3 = 0x63, NUMPAD4 = 0x64, NUMPAD5 = 0x65, NUMPAD6 = 0x66, NUMPAD7 = 0x67, NUMPAD8 = 0x68, NUMPAD9 = 0x69, MULTIPLY = 0x6a, ADD = 0x6b, SEPARATOR = 0x6c, SUBTRACT = 0x6d, DECIMAL = 0x6e, DIVIDE = 0x6f, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7a, F12 = 0x7b, F13 = 0x7c, F14 = 0x7d, F15 = 0x7e, F16 = 0x7f, F17 = 0x80, F18 = 0x81, F19 = 0x82, F20 = 0x83, F21 = 0x84, F22 = 0x85, F23 = 0x86, F24 = 0x87, NAVIGATION_VIEW = 0x88, NAVIGATION_MENU = 0x89, NAVIGATION_UP = 0x8a, NAVIGATION_DOWN = 0x8b, NAVIGATION_LEFT = 0x8c, NAVIGATION_RIGHT = 0x8d, NAVIGATION_ACCEPT = 0x8e, NAVIGATION_CANCEL = 0x8f, NUMLOCK = 0x90, SCROLL = 0x91, OEM_NEC_EQUAL = 0x92, OEM_FJ_JISHO = 0x92, OEM_FJ_MASSHOU = 0x93, OEM_FJ_TOUROKU = 0x94, OEM_FJ_LOYA = 0x95, OEM_FJ_ROYA = 0x96, LSHIFT = 0xa0, RSHIFT = 0xa1, LCONTROL = 0xa2, RCONTROL = 0xa3, LMENU = 0xa4, RMENU = 0xa5, BROWSER_BACK = 0xa6, BROWSER_FORWARD = 0xa7, BROWSER_REFRESH = 0xa8, BROWSER_STOP = 0xa9, BROWSER_SEARCH = 0xaa, BROWSER_FAVORITES = 0xab, BROWSER_HOME = 0xac, VOLUME_MUTE = 0xad, VOLUME_DOWN = 0xae, VOLUME_UP = 0xaf, MEDIA_NEXT_TRACK = 0xb0, MEDIA_PREV_TRACK = 0xb1, MEDIA_STOP = 0xb2, MEDIA_PLAY_PAUSE = 0xb3, LAUNCH_MAIL = 0xb4, LAUNCH_MEDIA_SELECT = 0xb5, LAUNCH_APP1 = 0xb6, LAUNCH_APP2 = 0xb7, OEM_1 = 0xba, OEM_PLUS = 0xbb, OEM_COMMA = 0xbc, OEM_MINUS = 0xbd, OEM_PERIOD = 0xbe, OEM_2 = 0xbf, OEM_3 = 0xc0, -- GAMEPAD_A = 0xc3, -- GAMEPAD_B = 0xc4, -- GAMEPAD_X = 0xc5, -- GAMEPAD_Y = 0xc6, -- GAMEPAD_RIGHT_SHOULDER = 0xc7, -- GAMEPAD_LEFT_SHOULDER = 0xc8, -- GAMEPAD_LEFT_TRIGGER = 0xc9, -- GAMEPAD_RIGHT_TRIGGER = 0xca, -- GAMEPAD_DPAD_UP = 0xcb, -- GAMEPAD_DPAD_DOWN = 0xcc, -- GAMEPAD_DPAD_LEFT = 0xcd, -- GAMEPAD_DPAD_RIGHT = 0xce, -- GAMEPAD_MENU = 0xcf, -- GAMEPAD_VIEW = 0xd0, -- GAMEPAD_LEFT_THUMBSTICK_BUTTON = 0xd1, -- GAMEPAD_RIGHT_THUMBSTICK_BUTTON = 0xd2, -- GAMEPAD_LEFT_THUMBSTICK_UP = 0xd3, -- GAMEPAD_LEFT_THUMBSTICK_DOWN = 0xd4, -- GAMEPAD_LEFT_THUMBSTICK_RIGHT = 0xd5, -- GAMEPAD_LEFT_THUMBSTICK_LEFT = 0xd6, -- GAMEPAD_RIGHT_THUMBSTICK_UP = 0xd7, -- GAMEPAD_RIGHT_THUMBSTICK_DOWN = 0xd8, -- GAMEPAD_RIGHT_THUMBSTICK_RIGHT = 0xd9, -- GAMEPAD_RIGHT_THUMBSTICK_LEFT = 0xda, OEM_4 = 0xdb, OEM_5 = 0xdc, OEM_6 = 0xdd, OEM_7 = 0xde, OEM_8 = 0xdf, OEM_AX = 0xe1, OEM_102 = 0xe2, ICO_HELP = 0xe3, ICO_00 = 0xe4, PROCESSKEY = 0xe5, ICO_CLEAR = 0xe6, PACKET = 0xe7, OEM_RESET = 0xe9, OEM_JUMP = 0xea, OEM_PA1 = 0xeb, OEM_PA2 = 0xec, OEM_PA3 = 0xed, OEM_WSCTRL = 0xee, OEM_CUSEL = 0xef, OEM_ATTN = 0xf0, OEM_FINISH = 0xf1, OEM_COPY = 0xf2, OEM_AUTO = 0xf3, OEM_ENLW = 0xf4, OEM_BACKTAB = 0xf5, ATTN = 0xf6, CRSEL = 0xf7, EXSEL = 0xf8, EREOF = 0xf9, PLAY = 0xfa, ZOOM = 0xfb, NONAME = 0xfc, PA1 = 0xfd, OEM_CLEAR = 0xfe, NUMPAD_RETURN = 0xf3, -- OEM_AUTO HANKAKU_ZENKAKU = 0xf4, -- OEM_ENLW SHIFT_LEFT = 0xa0, -- LSHIFT SHIFT_RIGHT = 0xa1, -- RSHIFT CONTROL_LEFT = 0xa2, -- LCONTROL CONTROL_RIGHT = 0xa3, -- RCONTROL ALT_LEFT = 0xa4, -- LMENU ALT_RIGHT = 0xa5, -- RMENU OS_LEFT = 0x5b, -- LWIN OS_RIGHT = 0x5c, -- RWIN }