repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
CrazyEddieTK/Zero-K | lups/ParticleClasses/OverdriveParticles.lua | 5 | 11148 | -- $Id: OverdriveParticles.lua 3345 2008-12-02 00:03:50Z jk $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local OverdriveParticles = {}
OverdriveParticles.__index = OverdriveParticles
local billShader,sizeUniform,frameUniform
local colormapUniform,colorsUniform = {},0
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function OverdriveParticles.GetInfo()
return {
name = "OverdriveParticles",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = 0, --// extreme simply z-ordering :x
--// gfx requirement
fbo = false,
shader = true,
rtt = false,
ctt = false,
}
end
OverdriveParticles.Default = {
particles = {},
dlist = 0,
--// visibility check
los = true,
airLos = true,
radar = false,
emitVector = {0,1,0},
pos = {0,0,0}, --// start pos
partpos = "0,0,0", --// particle relative start pos (can contain lua code!)
layer = 0,
life = 0,
lifeSpread = 0,
rot2Speed = 0, --// global effect rotation
size = 0,
sizeSpread = 0,
sizeGrowth = 0,
colormap = { {0, 0, 0, 0} }, --//max 12 entries
srcBlend = GL.ONE,
dstBlend = GL.ONE_MINUS_SRC_ALPHA,
alphaTest = 0, --FIXME
texture = '',
count = 1,
repeatEffect = false, --can be a number,too
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
--// speed ups
local abs = math.abs
local sqrt = math.sqrt
local rand = math.random
local twopi= 2*math.pi
local cos = math.cos
local sin = math.sin
local min = math.min
local spGetUnitLosState = Spring.GetUnitLosState
local spGetPositionLosState = Spring.GetPositionLosState
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitRadius = Spring.GetUnitRadius
local spGetProjectilePosition = Spring.GetProjectilePosition
local glTexture = gl.Texture
local glBlending = gl.Blending
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glCallList = gl.CallList
local glRotate = gl.Rotate
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
local GL_QUADS = GL.QUADS
local glMultiTexCoord= gl.MultiTexCoord
local glVertex = gl.Vertex
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function OverdriveParticles:CreateParticleAttributes(partpos,n)
local life, pos, size;
size = rand()*self.sizeSpread
life = self.life + rand()*self.lifeSpread
local part = {size=self.size+size,life=life,i=n}
pos = { ProcessParamCode(partpos, part) }
return life, size,
pos[1],pos[2],pos[3];
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local lasttexture = nil
function OverdriveParticles:BeginDraw()
gl.UseShader(billShader)
lasttexture = nil
end
function OverdriveParticles:EndDraw()
glTexture(false)
glBlending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA)
gl.UseShader(0)
end
function OverdriveParticles:Draw()
if (lasttexture ~= self.texture) then
glTexture(self.texture)
lasttexture = self.texture
end
glBlending(self.srcBlend,self.dstBlend)
glUniformInt(colorsUniform, self.ncolors)
for i = 1, min(self.ncolors+1,12) do
local color = self.colormap[i]
glUniform( colormapUniform[i] , color[1], color[2], color[3], color[4] )
end
glUniform(sizeUniform,self.usize)
glUniform(frameUniform,self.frame)
glPushMatrix()
glTranslate(self.pos[1],self.pos[2],self.pos[3])
glRotate(90,self.emitVector[1],self.emitVector[2],self.emitVector[3])
glRotate(self.rot2Speed*self.frame,0,1,0)
glCallList(self.dlist)
glPopMatrix()
end
local function DrawParticleForDList(size,life,x,y,z,colors)
glMultiTexCoord(0,x,y,z,1.0)
glMultiTexCoord(1,size,colors/life)
glVertex(-0.5,-0.5,0,0)
glVertex( 0.5,-0.5,1,0)
glVertex( 0.5, 0.5,1,1)
glVertex(-0.5, 0.5,0,1)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function OverdriveParticles:Initialize()
billShader = gl.CreateShader({
vertex = [[
uniform float size;
uniform float frame;
uniform vec4 colormap[12];
uniform int colors;
varying vec2 texCoord;
void main()
{
#define pos gl_MultiTexCoord0
#define csize gl_MultiTexCoord1.x
#define clrslife gl_MultiTexCoord1.y
#define texcoord gl_Vertex.pq
#define billboardpos gl_Vertex.xy
#define pos gl_MultiTexCoord0
#define csize gl_MultiTexCoord1.x
#define clrslife gl_MultiTexCoord1.y
#define texcoord gl_Vertex.pq
#define billboardpos gl_Vertex.xy
float cpos = frame*clrslife;
int ipos1 = int(cpos);
float psize = csize + size;
if (ipos1>colors || psize<=0.0) {
// paste dead particles offscreen, this way we don't dump the fragment shader with it
const vec4 offscreen = vec4(-2000.0,-2000.0,-2000.0,-2000.0);
gl_Position = offscreen;
}else{
int ipos2 = ipos1+1; if (ipos2>colors) ipos2 = colors;
gl_FrontColor = mix(colormap[ipos1],colormap[ipos2],fract(cpos));
// calc vertex position
gl_Position = gl_ModelViewMatrix * pos;
// offset vertex from center of the polygon
gl_Position.xy += billboardpos * psize;
// end
gl_Position = gl_ProjectionMatrix * gl_Position;
texCoord = texcoord;
}
}
]],
fragment = [[
uniform sampler2D tex0;
varying vec2 texCoord;
void main()
{
gl_FragColor = texture2D(tex0,texCoord) * gl_Color;
}
]],
uniformInt = {
tex0 = 0,
},
uniform = {
frame = 0,
size = 0,
},
})
if (billShader==nil) then
print(PRIO_MAJOR,"LUPS->OverdriveParticles: Critical Shader Error: " ..gl.GetShaderLog())
return false
end
sizeUniform = gl.GetUniformLocation(billShader,"size")
frameUniform = gl.GetUniformLocation(billShader,"frame")
colorsUniform = gl.GetUniformLocation(billShader,"colors")
for i=1,12 do
colormapUniform[i] = gl.GetUniformLocation(billShader,"colormap["..(i-1).."]")
end
end
function OverdriveParticles:Finalize()
gl.DeleteShader(billShader)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function OverdriveParticles:Update(n)
self.frame = self.frame + n
self.usize = self.usize + n*self.sizeGrowth
local gameFrame = math.ceil(Spring.GetGameFrame()/10)*10
if self.lastGameFrame and self.lastGameFrame >= gameFrame then
return
end
self.lastGameFrame = gameFrame
local cur_strength = math.min(4, Spring.GetUnitRulesParam(self.unit,"overdrive") or 1)
self.strength = 0.3*cur_strength + 0.7*(self.strength or 1)
local a = math.min(1, math.max(0,(self.strength-1)*0.35))
self.colormap = {BlendColor(self.color1,self.color2, a)}
self.usize = Blend(self.size1,self.size2, a)
end
-- used if repeatEffect=true;
function OverdriveParticles:ReInitialize()
self.usize = self.size
self.frame = 0
self.dieGameFrame = self.dieGameFrame + self.life + self.lifeSpread
end
function OverdriveParticles:CreateParticle()
local maxSpawnRadius = 0
self.ncolors = #self.colormap-1
self.partposCode = ParseParamString(self.partpos)
self.dlist = gl.CreateList(function()
gl.BeginEnd(GL.QUADS, function()
for i=1,self.count do
local life,size,x,y,z = self:CreateParticleAttributes(self.partposCode,i-1)
DrawParticleForDList(size,life,
x,y,z, -- relative start pos
self.ncolors)
local spawnDist = sqrt(x*x+y*y+z*z)
if (spawnDist>maxSpawnRadius) then maxSpawnRadius=spawnDist end
end
end)
end)
self.usize = self.size
self.frame = 0
self.firstGameFrame = Spring.GetGameFrame()
self.dieGameFrame = self.firstGameFrame + self.life + self.lifeSpread
--// visibility check vars
self.radius = self.size + self.sizeSpread + maxSpawnRadius + 100
self.sphereGrowth = self.sizeGrowth
end
function OverdriveParticles:Destroy()
for _,part in ipairs(self.particles) do
gl.DeleteList(part.dlist)
end
--gl.DeleteTexture(self.texture)
end
function OverdriveParticles:Visible()
local radius = self.radius +
self.frame*(self.sphereGrowth) --FIXME: frame is only updated on Update()
local posX,posY,posZ = self.pos[1],self.pos[2],self.pos[3]
local losState
if (self.unit and not self.worldspace) then
losState = GetUnitLosState(self.unit)
local ux,uy,uz = spGetUnitViewPosition(self.unit)
if not ux then
return false
end
radius = radius + (spGetUnitRadius(self.unit) or 0)
if self.noIconDraw then
if not Spring.IsUnitVisible(self.unit, radius, self.noIconDraw) then
return false
end
end
posX,posY,posZ = posX+ux,posY+uy,posZ+uz
elseif (self.projectile and not self.worldspace) then
local px,py,pz = spGetProjectilePosition(self.projectile)
posX,posY,posZ = posX+px,posY+py,posZ+pz
end
if (losState==nil) then
if (self.radar) then
losState = IsPosInRadar(posX,posY,posZ)
end
if ((not losState) and self.airLos) then
losState = IsPosInAirLos(posX,posY,posZ)
end
if ((not losState) and self.los) then
losState = IsPosInLos(posX,posY,posZ)
end
end
return (losState)and(spIsSphereInView(posX,posY,posZ,radius))
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function OverdriveParticles.Create(Options)
local newObject = MergeTable(Options, OverdriveParticles.Default)
setmetatable(newObject,OverdriveParticles) --// make handle lookup
newObject:CreateParticle()
return newObject
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return OverdriveParticles | gpl-2.0 |
czfshine/Don-t-Starve | data/DLC0001/scripts/prefabs/cavespiders.lua | 1 | 13067 | require "brains/spiderbrain"
require "stategraphs/SGspider"
local hiderassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider_caves.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local spitterassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider2_caves.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local dropperassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider_warrior.zip"),
Asset("ANIM", "anim/spider_white.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local prefabs =
{
"spidergland",
"monstermeat",
"silk",
"spider_web_spit",
}
local function ShouldAcceptItem(inst, item, giver)
if giver.prefab ~= "webber" then
return false
end
if inst.components.sleeper:IsAsleep() then
return false
end
if inst.components.eater:CanEat(item) then
return true
end
end
function GetOtherSpiders(inst)
local x,y,z = inst.Transform:GetWorldPosition()
local ents = TheSim:FindEntities(x,y,z, 15, {"spider"}, {"FX", "NOCLICK", "DECOR","INLIMBO"})
return ents
end
local function OnGetItemFromPlayer(inst, giver, item)
if inst.components.eater:CanEat(item) then
if inst.components.combat.target and inst.components.combat.target == giver then
inst.components.combat:SetTarget(nil)
elseif giver.components.leader then
inst.SoundEmitter:PlaySound("dontstarve/common/makeFriend")
giver.components.leader:AddFollower(inst)
local loyaltyTime = item.components.edible:GetHunger() * TUNING.SPIDER_LOYALTY_PER_HUNGER
inst.components.follower:AddLoyaltyTime(loyaltyTime)
end
local spiders = GetOtherSpiders(inst)
local maxSpiders = 3
for k,v in pairs(spiders) do
if maxSpiders < 0 then
break
end
if v.components.combat.target and v.components.combat.target == giver then
v.components.combat:SetTarget(nil)
elseif giver.components.leader then
v.SoundEmitter:PlaySound("dontstarve/common/makeFriend")
giver.components.leader:AddFollower(v)
local loyaltyTime = item.components.edible:GetHunger() * TUNING.SPIDER_LOYALTY_PER_HUNGER
print(loyaltyTime)
v.components.follower:AddLoyaltyTime(loyaltyTime)
end
maxSpiders = maxSpiders - 1
if v.components.sleeper:IsAsleep() then
v.components.sleeper:WakeUp()
end
end
item:Remove()
end
end
local function OnRefuseItem(inst, item)
inst.sg:GoToState("taunt")
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
local function Retarget(inst)
local targetDist = TUNING.SPIDER_WARRIOR_TARGET_DIST
if GetSeasonManager() and GetSeasonManager():IsSpring() then
targetDist = targetDist * TUNING.SPRING_COMBAT_MOD
end
return FindEntity(inst, targetDist, function(guy)
return ((guy:HasTag("character") and not guy:HasTag("monster")) or guy:HasTag("pig"))
and inst.components.combat:CanTarget(guy)
and not (inst.components.follower and inst.components.follower.leader == guy)
and not (inst.components.follower and inst.components.follower.leader == GetPlayer() and guy:HasTag("companion"))
end)
end
local function FindTargets(guy)
return (guy:HasTag("character") or guy:HasTag("pig"))
and inst.components.combat:CanTarget(guy)
and not (inst.components.follower and inst.components.follower.leader == guy)
end
local function keeptargetfn(inst, target)
return target
and target.components.combat
and target.components.health
and not target.components.health:IsDead()
and not (inst.components.follower and inst.components.follower.leader == target)
and not (inst.components.follower and inst.components.follower.leader == GetPlayer() and target:HasTag("companion"))
end
local function ShouldSleep(inst)
return GetClock():IsDay()
and not (inst.components.combat and inst.components.combat.target)
and not (inst.components.homeseeker and inst.components.homeseeker:HasHome() )
and not (inst.components.burnable and inst.components.burnable:IsBurning() )
and not (inst.components.follower and inst.components.follower.leader)
end
local function ShouldWake(inst)
return GetClock():IsNight()
or (inst.components.combat and inst.components.combat.target)
or (inst.components.homeseeker and inst.components.homeseeker:HasHome() )
or (inst.components.burnable and inst.components.burnable:IsBurning() )
or (inst.components.follower and inst.components.follower.leader)
or (inst:HasTag("spider_warrior") and FindEntity(inst, TUNING.SPIDER_WARRIOR_WAKE_RADIUS, function(...) return FindTargets(inst, ...) end ))
end
local function DoReturn(inst)
if inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home.components.childspawner then
inst.components.homeseeker.home.components.childspawner:GoHome(inst)
end
end
local function StartDay(inst)
if inst:IsAsleep() then
DoReturn(inst)
end
end
local function OnEntitySleep(inst)
if GetClock():IsDay() then
DoReturn(inst)
end
end
local function SummonFriends(inst, attacker)
local den = GetClosestInstWithTag("spiderden",inst, TUNING.SPIDER_SUMMON_WARRIORS_RADIUS)
if den and den.components.combat and den.components.combat.onhitfn then
den.components.combat.onhitfn(den, attacker)
end
end
local function OnAttacked(inst, data)
inst.components.combat:SetTarget(data.attacker)
inst.components.combat:ShareTarget(data.attacker, 30, function(dude)
return dude:HasTag("spider")
and not dude.components.health:IsDead()
and dude.components.follower
and dude.components.follower.leader == inst.components.follower.leader
end, 10)
end
local function WeaponDropped(inst)
inst:Remove()
end
local function SanityAura(inst, observer)
if observer.prefab == "webber" then
return 0
end
return -TUNING.SANITYAURA_SMALL
end
local function MakeWeapon(inst)
if inst.components.inventory then
local weapon = CreateEntity()
weapon.entity:AddTransform()
MakeInventoryPhysics(weapon)
weapon:AddComponent("weapon")
weapon.components.weapon:SetDamage(TUNING.SPIDER_SPITTER_DAMAGE_RANGED)
weapon.components.weapon:SetRange(inst.components.combat.attackrange, inst.components.combat.attackrange+4)
weapon.components.weapon:SetProjectile("spider_web_spit")
weapon:AddComponent("inventoryitem")
weapon.persists = false
weapon.components.inventoryitem:SetOnDroppedFn(function() WeaponDropped(weapon) end)
weapon:AddComponent("equippable")
inst.weapon = weapon
inst.components.inventory:Equip(inst.weapon)
inst.components.inventory:Unequip(EQUIPSLOTS.HANDS)
end
end
local function create_common()
local inst = CreateEntity()
inst:ListenForEvent( "daytime", function(i, data) StartDay( inst ) end, GetWorld())
inst.OnEntitySleep = OnEntitySleep
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.entity:AddLightWatcher()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 1.5, .5 )
inst.Transform:SetFourFaced()
----------
inst:AddTag("monster")
inst:AddTag("hostile")
inst:AddTag("scarytoprey")
inst:AddTag("canbetrapped")
MakeCharacterPhysics(inst, 10, .5)
inst:AddTag("spider")
inst.AnimState:SetBank("spider")
inst.AnimState:PlayAnimation("idle")
-- locomotor must be constructed before the stategraph!
inst:AddComponent("locomotor")
inst.components.locomotor:SetSlowMultiplier( 1 )
inst.components.locomotor:SetTriggersCreep(false)
inst.components.locomotor.pathcaps = { ignorecreep = true }
inst:SetStateGraph("SGspider")
inst:AddComponent("lootdropper")
inst.components.lootdropper:AddRandomLoot("monstermeat", 1)
inst.components.lootdropper:AddRandomLoot("silk", .5)
inst.components.lootdropper:AddRandomLoot("spidergland", .5)
inst.components.lootdropper.numrandomloot = 1
inst:AddComponent("follower")
inst.components.follower.maxfollowtime = TUNING.TOTAL_DAY_TIME
---------------------
MakeMediumBurnableCharacter(inst, "body")
MakeMediumFreezableCharacter(inst, "body")
inst.components.burnable.flammability = TUNING.SPIDER_FLAMMABILITY
---------------------
------------------
inst:AddComponent("health")
------------------
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "body"
inst.components.combat:SetKeepTargetFunction(keeptargetfn)
inst.components.combat:SetOnHit(SummonFriends)
inst.components.combat:SetHurtSound("dontstarve/creatures/cavespider/hit_response")
------------------
inst:AddComponent("sleeper")
inst.components.sleeper:SetResistance(2)
inst.components.sleeper:SetSleepTest(ShouldSleep)
inst.components.sleeper:SetWakeTest(ShouldWake)
------------------
inst:AddComponent("knownlocations")
------------------
inst:AddComponent("eater")
inst.components.eater:SetCarnivore()
inst.components.eater:SetCanEatHorrible()
inst.components.eater.strongstomach = true -- can eat monster meat!
------------------
inst:AddComponent("inspectable")
------------------
inst:AddComponent("trader")
inst.components.trader:SetAcceptTest(ShouldAcceptItem)
inst.components.trader.onaccept = OnGetItemFromPlayer
inst.components.trader.onrefuse = OnRefuseItem
------------------
inst:AddComponent("sanityaura")
inst.components.sanityaura.aurafn = SanityAura
local brain = require "brains/spiderbrain"
inst:SetBrain(brain)
inst:ListenForEvent("attacked", OnAttacked)
--inst:ListenForEvent("dusktime", function() StartNight(inst) end, GetWorld())
return inst
end
local function create_hider()
local inst = create_common()
inst.AnimState:SetBank("spider_hider")
inst.AnimState:SetBuild("DS_spider_caves")
--inst:AddTag("spider_warrior")
inst.components.health:SetMaxHealth(TUNING.SPIDER_HIDER_HEALTH)
inst:AddTag("spider_hider")
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_HIDER_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_HIDER_ATTACK_PERIOD)
inst.components.combat:SetRetargetFunction(1, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_HIDER_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_HIDER_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
return inst
end
local function create_spitter()
local inst = create_common()
inst.AnimState:SetBank("spider_spitter")
inst.AnimState:SetBuild("DS_spider2_caves")
inst:AddTag("spider_spitter")
inst:AddComponent("inventory")
inst.components.health:SetMaxHealth(TUNING.SPIDER_SPITTER_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_SPITTER_DAMAGE_MELEE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_SPITTER_ATTACK_PERIOD + math.random()*2)
inst.components.combat:SetRange(TUNING.SPIDER_SPITTER_ATTACK_RANGE, TUNING.SPIDER_SPITTER_HIT_RANGE)
inst.components.combat:SetRetargetFunction(2, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_SPITTER_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_SPITTER_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
MakeWeapon(inst)
return inst
end
local function create_dropper()
local inst = create_common()
inst.AnimState:SetBuild("spider_white")
inst:AddTag("spider_warrior")
inst.components.health:SetMaxHealth(TUNING.SPIDER_WARRIOR_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_WARRIOR_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_WARRIOR_ATTACK_PERIOD + math.random()*2)
inst.components.combat:SetRange(TUNING.SPIDER_WARRIOR_ATTACK_RANGE, TUNING.SPIDER_WARRIOR_HIT_RANGE)
inst.components.combat:SetRetargetFunction(2, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_WARRIOR_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_WARRIOR_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
return inst
end
return Prefab("cave/monsters/spider_hider", create_hider, hiderassets, prefabs),
Prefab("cave/monsters/spider_spitter", create_spitter, spitterassets, prefabs),
Prefab("cave/monsters/spider_dropper", create_dropper, dropperassets, prefabs)
| gpl-2.0 |
alexgrist/NutScript | gamemode/core/derma/cl_character.lua | 1 | 13938 |
local gradient = surface.GetTextureID("vgui/gradient-d")
local audioFadeInTime = 2
local animationTime = 0.5
local matrixZScale = Vector(1, 1, 0.0001)
-- character menu panel
DEFINE_BASECLASS("ixSubpanelParent")
local PANEL = {}
function PANEL:Init()
self:SetSize(self:GetParent():GetSize())
self:SetPos(0, 0)
self.childPanels = {}
self.subpanels = {}
self.activeSubpanel = ""
self.currentDimAmount = 0
self.currentY = 0
self.currentScale = 1
self.currentAlpha = 255
self.targetDimAmount = 255
self.targetScale = 0.9
end
function PANEL:Dim(length, callback)
length = length or animationTime
self.currentDimAmount = 0
self:CreateAnimation(length, {
target = {
currentDimAmount = self.targetDimAmount,
currentScale = self.targetScale
},
easing = "outCubic",
OnComplete = callback
})
self:OnDim()
end
function PANEL:Undim(length, callback)
length = length or animationTime
self.currentDimAmount = self.targetDimAmount
self:CreateAnimation(length, {
target = {
currentDimAmount = 0,
currentScale = 1
},
easing = "outCubic",
OnComplete = callback
})
self:OnUndim()
end
function PANEL:OnDim()
end
function PANEL:OnUndim()
end
function PANEL:Paint(width, height)
local amount = self.currentDimAmount
local bShouldScale = self.currentScale != 1
local matrix
-- draw child panels with scaling if needed
if (bShouldScale) then
matrix = Matrix()
matrix:Scale(matrixZScale * self.currentScale)
matrix:Translate(Vector(
ScrW() * 0.5 - (ScrW() * self.currentScale * 0.5),
ScrH() * 0.5 - (ScrH() * self.currentScale * 0.5),
1
))
cam.PushModelMatrix(matrix)
self.currentMatrix = matrix
end
BaseClass.Paint(self, width, height)
if (bShouldScale) then
cam.PopModelMatrix()
self.currentMatrix = nil
end
if (amount > 0) then
local color = Color(0, 0, 0, amount)
surface.SetDrawColor(color)
surface.DrawRect(0, 0, width, height)
end
end
vgui.Register("ixCharMenuPanel", PANEL, "ixSubpanelParent")
-- character menu main button list
PANEL = {}
function PANEL:Init()
local parent = self:GetParent()
self:SetSize(parent:GetWide() * 0.25, parent:GetTall())
self:GetVBar():SetWide(0)
self:GetVBar():SetVisible(false)
end
function PANEL:Add(name)
local panel = vgui.Create(name, self)
panel:Dock(TOP)
return panel
end
function PANEL:SizeToContents()
self:GetCanvas():InvalidateLayout(true)
-- if the canvas has extra space, forcefully dock to the bottom so it doesn't anchor to the top
if (self:GetTall() > self:GetCanvas():GetTall()) then
self:GetCanvas():Dock(BOTTOM)
else
self:GetCanvas():Dock(NODOCK)
end
end
vgui.Register("ixCharMenuButtonList", PANEL, "DScrollPanel")
-- main character menu panel
PANEL = {}
AccessorFunc(PANEL, "bUsingCharacter", "UsingCharacter", FORCE_BOOL)
function PANEL:Init()
local parent = self:GetParent()
local padding = self:GetPadding()
local halfWidth = ScrW() * 0.5
local halfPadding = padding * 0.5
local bHasCharacter = #ix.characters > 0
self.bUsingCharacter = LocalPlayer().GetCharacter and LocalPlayer():GetCharacter()
self:DockPadding(padding, padding, padding, padding)
local infoLabel = self:Add("DLabel")
infoLabel:SetTextColor(Color(255, 255, 255, 25))
infoLabel:SetFont("ixMenuMiniFont")
infoLabel:SetText(L("helix") .. " " .. GAMEMODE.Version)
infoLabel:SizeToContents()
infoLabel:SetPos(ScrW() - infoLabel:GetWide() - 4, ScrH() - infoLabel:GetTall() - 4)
local logoPanel = self:Add("Panel")
logoPanel:SetSize(ScrW(), ScrH() * 0.25)
logoPanel:SetPos(0, ScrH() * 0.25)
logoPanel.Paint = function(panel, width, height)
local matrix = self.currentMatrix
-- don't scale the background because it fucks the blur
if (matrix) then
cam.PopModelMatrix()
end
local newHeight = Lerp(1 - (self.currentDimAmount / 255), 0, height)
local y = height * 0.5 - newHeight * 0.5
local _, screenY = panel:LocalToScreen(0, 0)
screenY = screenY + y
render.SetScissorRect(0, screenY, width, screenY + newHeight, true)
ix.util.DrawBlur(panel, 15, nil, 200)
-- background dim
surface.SetDrawColor(0, 0, 0, 100)
surface.DrawRect(0, y, width, newHeight)
-- border lines
surface.SetDrawColor(ix.config.Get("color") or color_white)
surface.DrawRect(0, y, width, 1)
surface.DrawRect(0, y + newHeight - 1, width, 1)
if (matrix) then
cam.PushModelMatrix(matrix)
end
for _, v in ipairs(panel:GetChildren()) do
v:PaintManual()
end
render.SetScissorRect(0, 0, 0, 0, false)
end
-- draw schema logo material instead of text if available
local logo = Schema.logo and ix.util.GetMaterial(Schema.logo)
if (logo and !logo:IsError()) then
local logoImage = logoPanel:Add("DImage")
logoImage:SetMaterial(logo)
logoImage:SetSize(halfWidth, halfWidth * logo:Height() / logo:Width())
logoImage:SetPos(halfWidth - logoImage:GetWide() * 0.5, halfPadding)
logoImage:SetPaintedManually(true)
logoPanel:SetTall(logoImage:GetTall() + padding)
else
local newHeight = padding
local subtitle = L2("schemaDesc") or Schema.description
local titleLabel = logoPanel:Add("DLabel")
titleLabel:SetTextColor(color_white)
titleLabel:SetFont("ixTitleFont")
titleLabel:SetText(L2("schemaName") or Schema.name or L"unknown")
titleLabel:SizeToContents()
titleLabel:SetPos(halfWidth - titleLabel:GetWide() * 0.5, halfPadding)
titleLabel:SetPaintedManually(true)
newHeight = newHeight + titleLabel:GetTall()
if (subtitle) then
local subtitleLabel = logoPanel:Add("DLabel")
subtitleLabel:SetTextColor(color_white)
subtitleLabel:SetFont("ixSubTitleFont")
subtitleLabel:SetText(subtitle)
subtitleLabel:SizeToContents()
subtitleLabel:SetPos(halfWidth - subtitleLabel:GetWide() * 0.5, 0)
subtitleLabel:MoveBelow(titleLabel)
subtitleLabel:SetPaintedManually(true)
newHeight = newHeight + subtitleLabel:GetTall()
end
logoPanel:SetTall(newHeight)
end
-- button list
self.mainButtonList = self:Add("ixCharMenuButtonList")
self.mainButtonList:Dock(LEFT)
-- create character button
local createButton = self.mainButtonList:Add("ixMenuButton")
createButton:SetText("create")
createButton:SizeToContents()
createButton.DoClick = function()
local maximum = hook.Run("GetMaxPlayerCharacter", LocalPlayer()) or ix.config.Get("maxCharacters", 5)
-- don't allow creation if we've hit the character limit
if (#ix.characters >= maximum) then
self:GetParent():ShowNotice(3, L("maxCharacters"))
return
end
self:Dim()
parent.newCharacterPanel:SetActiveSubpanel("faction", 0)
parent.newCharacterPanel:SlideUp()
end
-- load character button
self.loadButton = self.mainButtonList:Add("ixMenuButton")
self.loadButton:SetText("load")
self.loadButton:SizeToContents()
self.loadButton.DoClick = function()
self:Dim()
parent.loadCharacterPanel:SlideUp()
end
if (!bHasCharacter) then
self.loadButton:SetDisabled(true)
end
-- community button
local extraURL = ix.config.Get("communityURL", "")
local extraText = ix.config.Get("communityText", "@community")
if (extraURL != "" and extraText != "") then
if (extraText:sub(1, 1) == "@") then
extraText = L(extraText:sub(2))
end
local extraButton = self.mainButtonList:Add("ixMenuButton")
extraButton:SetText(extraText, true)
extraButton:SizeToContents()
extraButton.DoClick = function()
gui.OpenURL(extraURL)
end
end
-- leave/return button
self.returnButton = self.mainButtonList:Add("ixMenuButton")
self:UpdateReturnButton()
self.returnButton.DoClick = function()
if (self.bUsingCharacter) then
parent:Close()
else
RunConsoleCommand("disconnect")
end
end
self.mainButtonList:SizeToContents()
end
function PANEL:UpdateReturnButton(bValue)
if (bValue != nil) then
self.bUsingCharacter = bValue
end
self.returnButton:SetText(self.bUsingCharacter and "return" or "leave")
self.returnButton:SizeToContents()
end
function PANEL:OnDim()
-- disable input on this panel since it will still be in the background while invisible - prone to stray clicks if the
-- panels overtop slide out of the way
self:SetMouseInputEnabled(false)
self:SetKeyboardInputEnabled(false)
end
function PANEL:OnUndim()
self:SetMouseInputEnabled(true)
self:SetKeyboardInputEnabled(true)
-- we may have just deleted a character so update the status of the return button
self.bUsingCharacter = LocalPlayer().GetCharacter and LocalPlayer():GetCharacter()
self:UpdateReturnButton()
end
function PANEL:OnClose()
for _, v in pairs(self:GetChildren()) do
if (IsValid(v)) then
v:SetVisible(false)
end
end
end
function PANEL:PerformLayout(width, height)
local padding = self:GetPadding()
self.mainButtonList:SetPos(padding, height - self.mainButtonList:GetTall() - padding)
end
vgui.Register("ixCharMenuMain", PANEL, "ixCharMenuPanel")
-- container panel
PANEL = {}
function PANEL:Init()
if (IsValid(ix.gui.loading)) then
ix.gui.loading:Remove()
end
if (IsValid(ix.gui.characterMenu)) then
if (IsValid(ix.gui.characterMenu.channel)) then
ix.gui.characterMenu.channel:Stop()
end
ix.gui.characterMenu:Remove()
end
self:SetSize(ScrW(), ScrH())
self:SetPos(0, 0)
-- main menu panel
self.mainPanel = self:Add("ixCharMenuMain")
-- new character panel
self.newCharacterPanel = self:Add("ixCharMenuNew")
self.newCharacterPanel:SlideDown(0)
-- load character panel
self.loadCharacterPanel = self:Add("ixCharMenuLoad")
self.loadCharacterPanel:SlideDown(0)
-- notice bar
self.notice = self:Add("ixNoticeBar")
-- finalization
self:MakePopup()
self.currentAlpha = 255
self.volume = 0
ix.gui.characterMenu = self
if (!IsValid(ix.gui.intro)) then
self:PlayMusic()
end
hook.Run("OnCharacterMenuCreated", self)
end
function PANEL:PlayMusic()
local path = "sound/" .. ix.config.Get("music")
local url = path:match("http[s]?://.+")
local play = url and sound.PlayURL or sound.PlayFile
path = url and url or path
play(path, "noplay", function(channel, error, message)
if (!IsValid(self) or !IsValid(channel)) then
return
end
channel:SetVolume(self.volume or 0)
channel:Play()
self.channel = channel
self:CreateAnimation(audioFadeInTime, {
index = 10,
target = {volume = 1},
Think = function(animation, panel)
if (IsValid(panel.channel)) then
panel.channel:SetVolume(self.volume * 0.5)
end
end
})
end)
end
function PANEL:ShowNotice(type, text)
self.notice:SetType(type)
self.notice:SetText(text)
self.notice:Show()
end
function PANEL:HideNotice()
if (IsValid(self.notice) and !self.notice:GetHidden()) then
self.notice:Slide("up", 0.5, true)
end
end
function PANEL:OnCharacterDeleted(character)
if (#ix.characters == 0) then
self.mainPanel.loadButton:SetDisabled(true)
self.mainPanel:Undim() -- undim since the load panel will slide down
else
self.mainPanel.loadButton:SetDisabled(false)
end
self.loadCharacterPanel:OnCharacterDeleted(character)
end
function PANEL:OnCharacterLoadFailed(error)
self.loadCharacterPanel:SetMouseInputEnabled(true)
self.loadCharacterPanel:SlideUp()
self:ShowNotice(3, error)
end
function PANEL:IsClosing()
return self.bClosing
end
function PANEL:Close(bFromMenu)
self.bClosing = true
self.bFromMenu = bFromMenu
local fadeOutTime = animationTime * 8
self:CreateAnimation(fadeOutTime, {
index = 1,
target = {currentAlpha = 0},
Think = function(animation, panel)
panel:SetAlpha(panel.currentAlpha)
end,
OnComplete = function(animation, panel)
panel:Remove()
end
})
self:CreateAnimation(fadeOutTime - 0.1, {
index = 10,
target = {volume = 0},
Think = function(animation, panel)
if (IsValid(panel.channel)) then
panel.channel:SetVolume(self.volume * 0.5)
end
end,
OnComplete = function(animation, panel)
if (IsValid(panel.channel)) then
panel.channel:Stop()
panel.channel = nil
end
end
})
-- hide children if we're already dimmed
if (bFromMenu) then
for _, v in pairs(self:GetChildren()) do
if (IsValid(v)) then
v:SetVisible(false)
end
end
else
-- fade out the main panel quicker because it significantly blocks the screen
self.mainPanel.currentAlpha = 255
self.mainPanel:CreateAnimation(animationTime * 2, {
target = {currentAlpha = 0},
easing = "outQuint",
Think = function(animation, panel)
panel:SetAlpha(panel.currentAlpha)
end,
OnComplete = function(animation, panel)
panel:SetVisible(false)
end
})
end
-- relinquish mouse control
self:SetMouseInputEnabled(false)
self:SetKeyboardInputEnabled(false)
gui.EnableScreenClicker(false)
end
function PANEL:Paint(width, height)
surface.SetTexture(gradient)
surface.SetDrawColor(0, 0, 0, 255)
surface.DrawTexturedRect(0, 0, width, height)
if (!ix.option.Get("cheapBlur", false)) then
surface.SetDrawColor(0, 0, 0, 150)
surface.DrawTexturedRect(0, 0, width, height)
ix.util.DrawBlur(self, Lerp((self.currentAlpha - 200) / 255, 0, 10))
end
end
function PANEL:PaintOver(width, height)
if (self.bClosing and self.bFromMenu) then
surface.SetDrawColor(color_black)
surface.DrawRect(0, 0, width, height)
end
end
function PANEL:OnRemove()
if (self.channel) then
self.channel:Stop()
self.channel = nil
end
end
vgui.Register("ixCharMenu", PANEL, "EditablePanel")
if (IsValid(ix.gui.characterMenu)) then
ix.gui.characterMenu:Remove()
--TODO: REMOVE ME
ix.gui.characterMenu = vgui.Create("ixCharMenu")
end
| mit |
blueyed/awesome | tests/test-awful-widget-button.lua | 5 | 3006 | local runner = require( "_runner" )
local wibox = require( "wibox" )
local awful = require( "awful" )
local beautiful = require( "beautiful" )
local gtable = require("gears.table")
local steps = {}
local w
local img
local button
-- Also check recursive signals from events
local layout
local got_called = false
-- create a wibox.
table.insert(steps, function()
w = wibox {
ontop = true,
width = 250,
height = 250,
visible = true,
}
button = awful.widget.button {
image = beautiful.awesome_icon
}
w : setup {
{
{
text = "foo",
widget = wibox.widget.textbox,
},
bg = "#ff0000",
widget = wibox.container.background
},
{
{
widget = button,
},
bg = "#ff00ff",
widget = wibox.container.background
},
{
{
text = "foo",
widget = wibox.widget.textbox,
},
bg = "#0000ff",
widget = wibox.container.background
},
layout = wibox.layout.flex.vertical
}
awful.placement.centered(w)
img = button._private.image
assert(img)
-- Test the click
layout = w.widget
assert(layout)
button:buttons(gtable.join(
button:buttons(),
awful.button({}, 1, nil, function ()
button:emit_signal_recursive("test::recursive")
end)
))
layout:connect_signal("test::recursive", function()
got_called = true
end)
return true
end)
-- Test a button press
table.insert(steps, function()
awful.placement.centered(mouse)
root.fake_input("button_press", 1)
awesome.sync()
return true
end)
table.insert(steps, function()
assert(button._private.image ~= img)
return true
end)
-- Test a button release
table.insert(steps, function()
assert(button._private.image ~= img)
root.fake_input("button_release", 1)
awesome.sync()
return true
end)
-- Test a button press/release outside of the widget
table.insert(steps, function()
assert(button._private.image == img)
root.fake_input("button_press", 1)
awesome.sync()
return true
end)
table.insert(steps, function()
assert(button._private.image ~= img)
return true
end)
table.insert(steps, function()
-- just make sure the button is not released for nothing
assert(button._private.image ~= img)
-- test if the button is released when the mouse move out
awful.placement.right(mouse--[[, {parent = w}]])
root.fake_input("button_release", 1)
awesome.sync()
return true
end)
table.insert(steps, function()
assert(button._private.image == img)
-- The button had plenty of clicks by now. Make sure everything worked
assert(got_called)
return true
end)
runner.run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
CrazyEddieTK/Zero-K | units/commsupport1.lua | 5 | 5827 | unitDef = {
unitname = [[commsupport1]],
name = [[Support Commander]],
description = [[Econ/Support Commander, Builds at 12 m/s]],
acceleration = 0.25,
activateWhenBuilt = true,
autoHeal = 5,
brakeRate = 0.45,
buildCostMetal = 1200,
buildDistance = 250,
builder = true,
buildoptions = {
},
buildPic = [[commsupport.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[45 50 45]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
level = [[1]],
statsname = [[dynsupport1]],
soundok = [[heavy_bot_move]],
soundselect = [[bot_select]],
soundbuild = [[builder_start]],
commtype = [[4]],
aimposoffset = [[0 15 0]],
},
energyMake = 6,
energyStorage = 500,
energyUse = 0,
explodeAs = [[ESTOR_BUILDINGEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[commander1]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
losEmitHeight = 40,
maxDamage = 2000,
maxSlope = 36,
maxVelocity = 1.2,
maxWaterDepth = 5000,
metalMake = 4,
metalStorage = 500,
minCloakDistance = 75,
movementClass = [[AKBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]],
objectName = [[commsupport.s3o]],
script = [[commsupport.lua]],
selfDestructAs = [[ESTOR_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:flashmuzzle1]],
[[custom:NONE]],
},
},
showNanoSpray = false,
showPlayerName = true,
sightDistance = 500,
sonarDistance = 300,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 1350,
upright = true,
workerTime = 12,
weapons = {
[1] = {
def = [[FAKELASER]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
[5] = {
def = [[GAUSS]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
FAKELASER = {
name = [[Fake Laser]],
areaOfEffect = 12,
beamTime = 0.1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 0,
},
duration = 0.11,
explosionGenerator = [[custom:flash1green]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
laserFlareSize = 5.53,
minIntensity = 1,
range = 450,
reloadtime = 0.11,
rgbColor = [[0 1 0]],
sweepfire = false,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 5.53,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 900,
},
GAUSS = {
name = [[Gauss Rifle]],
alphaDecay = 0.12,
areaOfEffect = 16,
avoidfeature = false,
bouncerebound = 0.15,
bounceslip = 1,
cegTag = [[gauss_tag_l]],
craterBoost = 0,
craterMult = 0,
damage = {
default = 140,
planes = 140,
subs = 8,
},
customParams = {
single_hit = true,
},
explosionGenerator = [[custom:gauss_hit_l]],
groundbounce = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 0,
noExplode = true,
noSelfDamage = true,
numbounce = 40,
range = 420,
reloadtime = 2.5,
rgbColor = [[0.5 1 1]],
separation = 0.5,
size = 0.8,
sizeDecay = -0.1,
soundHit = [[weapon/gauss_hit]],
soundHitVolume = 3,
soundStart = [[weapon/gauss_fire]],
soundStartVolume = 2.5,
stages = 32,
turret = true,
waterbounce = 1,
weaponType = [[Cannon]],
weaponVelocity = 2200,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[commsupport_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ commsupport1 = unitDef })
| gpl-2.0 |
starkos/premake-core | modules/gmake2/tests/test_gmake2_makefile.lua | 12 | 1686 | --
-- test_gmake2_makefile.lua
-- Validate the makefile projects.
-- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project
--
local p = premake
local suite = test.declare("gmake2_makefile")
local p = premake
local gmake2 = p.modules.gmake2
local project = p.project
--
-- Setup
--
local wks, prj
function suite.setup()
wks, prj = test.createWorkspace()
kind "Makefile"
end
local function prepare()
prj = test.getproject(wks, 1)
gmake2.makefile.configs(prj)
end
--
-- Check rules for Makefile projects.
--
function suite.makefile_configs_empty()
prepare()
test.capture [[
ifeq ($(config),debug)
TARGETDIR = bin/Debug
TARGET = $(TARGETDIR)/MyProject
define BUILDCMDS
endef
define CLEANCMDS
endef
else ifeq ($(config),release)
TARGETDIR = bin/Release
TARGET = $(TARGETDIR)/MyProject
define BUILDCMDS
endef
define CLEANCMDS
endef
else
$(error "invalid configuration $(config)")
endif
]]
end
function suite.makefile_configs_commands()
buildcommands {
"touch source"
}
cleancommands {
"rm -f source"
}
prepare()
test.capture [[
ifeq ($(config),debug)
TARGETDIR = bin/Debug
TARGET = $(TARGETDIR)/MyProject
define BUILDCMDS
@echo Running build commands
touch source
endef
define CLEANCMDS
@echo Running clean commands
rm -f source
endef
else ifeq ($(config),release)
TARGETDIR = bin/Release
TARGET = $(TARGETDIR)/MyProject
define BUILDCMDS
@echo Running build commands
touch source
endef
define CLEANCMDS
@echo Running clean commands
rm -f source
endef
else
$(error "invalid configuration $(config)")
endif
]]
end
| bsd-3-clause |
czfshine/Don-t-Starve | data/DLC0001/scripts/components/combat.lua | 1 | 28206 |
local Combat = Class(function(self, inst)
self.inst = inst
self.nextbattlecrytime = nil
self.attackrange = 3
self.hitrange = 3
self.areahitrange = nil
self.areahitdamagepercent = nil
self.defaultdamage = 0
self.playerdamagepercent = 1
self.min_attack_period = 4
self.onhitfn = nil
self.onhitotherfnonhitotherfn = nil
self.laststartattacktime = 0
self.keeptargetfn = nil
self.keeptargettimeout = 0
self.hiteffectsymbol = "marker"
self.canattack = true
self.lasttargetGUID = nil
self.inst:AddTag("hascombatcomponent") self.inst:AddTag("combat")
self.forcefacing = true
self.battlecryenabled = true
end)
function Combat:SetAttackPeriod(period)
self.min_attack_period = period
end
function Combat:InCooldown()
if self.laststartattacktime then
local time_since_doattack = GetTime() - self.laststartattacktime
if time_since_doattack < self.min_attack_period then
return true
end
end
return false
end
function Combat:SetRange(attack, hit)
self.attackrange = attack
self.hitrange = hit or self.attackrange
end
function Combat:SetAreaDamage(range, percent)
self.areahitrange = range
if self.areahitrange then
self.areahitdamagepercent = percent or 1
else
self.areahitdamagepercent = nil
end
end
function Combat:BlankOutAttacks(fortime)
self.canattack = false
if self.blanktask then
self.blanktask:Cancel()
end
self.blanktask = self.inst:DoTaskInTime(fortime, function() self.canattack = true self.blanktask = nil end)
end
function Combat:ShareTarget(target, range, fn, maxnum)
--print("Combat:ShareTarget", self.inst, target)
local x,y,z = self.inst.Transform:GetWorldPosition()
local ents = nil
if GetSeasonManager() and GetSeasonManager():IsSpring() then
ents = TheSim:FindEntities(x,y,z, range * TUNING.SPRING_COMBAT_MOD)
else
ents = TheSim:FindEntities(x,y,z, range)
end
if ents then
local num_helpers = 0
for k,v in pairs(ents) do
if v ~= self.inst and v.components.combat and not (v.components.health and v.components.health:IsDead()) and fn(v) then
--print(" share with", v)
if v.components.combat:SuggestTarget(target) then
num_helpers = num_helpers + 1
end
end
if num_helpers >= maxnum then
break
end
end
end
end
function Combat:SetDefaultDamage(damage)
self.defaultdamage = damage
end
function Combat:SetOnHit(fn)
self.onhitfn = fn
end
function Combat:SuggestTarget(target)
if not self.target and target ~= nil then
--print("Combat:SuggestTarget", self.inst, target)
self:SetTarget(target)
return true
end
end
function Combat:SetKeepTargetFunction(fn)
self.keeptargetfn = fn
end
function tryretarget(inst)
inst.components.combat:TryRetarget()
end
function Combat:TryRetarget()
if self.targetfn then
if not (self.inst.components.health and self.inst.components.health:IsDead() )
and not (self.inst.components.sleeper and self.inst.components.sleeper:IsInDeepSleep()) then
local newtarget = self.targetfn(self.inst)
if newtarget and newtarget ~= self.target and not newtarget:HasTag("notarget") then
if self.target and self.target:HasTag("structure") and not newtarget:HasTag("structure") then
self:SetTarget(newtarget)
else
self:SuggestTarget(newtarget)
end
end
end
end
end
function Combat:SetRetargetFunction(period, fn)
self.targetfn = fn
self.retargetperiod = period
if self.retargettask then
self.retargettask:Cancel()
self.retargettask = nil
end
if period and fn then
self.retargettask = self.inst:DoPeriodicTask(period, tryretarget)
end
end
function Combat:OnEntitySleep()
if self.retargettask then
self.retargettask:Cancel()
self.retargettask = nil
end
end
function Combat:OnEntityWake()
if self.retargettask then
self.retargettask:Cancel()
self.retargettask = nil
end
if self.retargetperiod then
self.retargettask = self.inst:DoPeriodicTask(self.retargetperiod, tryretarget)
end
end
function Combat:OnUpdate(dt)
if not self.target then
self.inst:StopUpdatingComponent(self)
return
end
if self.keeptargetfn then
self.keeptargettimeout = self.keeptargettimeout - dt
if self.keeptargettimeout < 0 then
self.keeptargettimeout = 1
if not self.target:IsValid() or
not self.keeptargetfn(self.inst, self.target) or not
(self.target and self.target.components.combat and self.target.components.combat:CanBeAttacked(self.inst)) then
self.inst:PushEvent("losttarget")
self:SetTarget(nil)
end
end
end
end
function Combat:IsRecentTarget(target)
return target and (target == self.target or target.GUID == self.lasttargetGUID)
end
function Combat:TargetIs(target)
return self.target and self.target == target
end
function Combat:SetTarget(target)
local new = target ~= self.target
local player = GetPlayer()
if new and (not target or self:IsValidTarget(target) ) and not (target and target.sg and target.sg:HasStateTag("hiding") and target:HasTag("player")) then
if METRICS_ENABLED and self.target == player and new ~= player then
FightStat_GaveUp(self.inst)
end
if self.target then
self.lasttargetGUID = self.target.GUID
else
self.lasttargetGUID = nil
end
local oldtarget = self.target
self.target = target
self.inst:PushEvent("newcombattarget", {target=target, oldtarget=oldtarget})
if METRICS_ENABLED and (player == target or target and target.components.follower and target.components.follower.leader == player) then
FightStat_Targeted(self.inst)
end
if target and self.keeptargetfn then
self.inst:StartUpdatingComponent(self)
else
self.inst:StopUpdatingComponent(self)
end
if target and self.inst.components.follower and self.inst.components.follower.leader == target and self.inst.components.follower.leader.components.leader then
self.inst.components.follower.leader.components.leader:RemoveFollower(self.inst)
end
end
end
function Combat:IsValidTarget(target)
if target
and target.components.burnable
and target.components.burnable.canlight
and not target.components.burnable:IsBurning()
and not target:HasTag("burnt")
and self:GetWeapon() and self:GetWeapon():HasTag("rangedlighter") then
return true
elseif target
and target.components.burnable
and (target.components.burnable:IsSmoldering() or target.components.burnable:IsBurning())
and self:GetWeapon() and self:GetWeapon():HasTag("extinguisher") then
return true
elseif not target
or not target.entity:IsValid()
or not target.components
or not target.components.combat
or not target.entity:IsVisible()
or not target.components.health
or target == self.inst
or target.components.health:IsDead()
or (target:HasTag("shadow") and not self.inst.components.sanity)
or Vector3(target.Transform:GetWorldPosition()).y > self.attackrange then
return false
else
if self.notags then
for i,v in pairs(self.notags) do
if target:HasTag(v) then
return false
end
end
return true
else
return true
end
end
end
function Combat:ValidateTarget()
if self.target then
if self:IsValidTarget(self.target) then
return true
else
self:SetTarget(nil)
end
end
end
function Combat:GetDebugString()
local str = string.format("target:%s, damage:%d", tostring(self.target), self.defaultdamage or 0 )
if self.target then
local dist = math.sqrt(self.inst:GetDistanceSqToInst(self.target)) or 0
local atkrange = math.sqrt(self:CalcAttackRangeSq()) or 0
str = str .. string.format(" dist/range: %2.2f/%2.2f", dist, atkrange)
end
if self.targetfn and self.retargetperiod then
str = str.. " Retarget set"
end
str = str..string.format(" can attack:%s", tostring(self:CanAttack(self.target)))
str = str..string.format(" can be attacked: %s", tostring(self:CanBeAttacked()))
return str
end
function Combat:GetGiveUpString(target)
return nil
end
function Combat:GiveUp()
if self.inst.components.talker then
local str = self:GetGiveUpString(self.target)
if str then
self.inst.components.talker:Say(str)
end
end
if METRICS_ENABLED and GetPlayer() == self.target then
FightStat_GaveUp(self.inst)
end
self.inst:PushEvent("giveuptarget", {target = self.target})
if self.target then
self.lasttargetGUID = self.target.GUID
end
self.target = nil
end
function Combat:GetBattleCryString(target)
return nil
end
function Combat:BattleCry()
if self.battlecryenabled and (not self.nextbattlecrytime or GetTime() > self.nextbattlecrytime) then
self.nextbattlecrytime = GetTime() + (self.battlecryinterval and self.battlecryinterval or 5)+math.random()*3
if self.inst.components.talker then
local cry = self:GetBattleCryString(self.target)
if cry then
self.inst.components.talker:Say{Line(cry, 2)}
end
elseif self.inst.sg.sg.states.taunt and not self.inst.sg:HasStateTag("busy") then
self.inst.sg:GoToState("taunt")
end
end
end
function Combat:SetHurtSound(sound)
self.hurtsound = sound
end
function Combat:GetAttacked(attacker, damage, weapon, stimuli)
--print ("ATTACKED", self.inst, attacker, damage)
local blocked = false
local player = GetPlayer()
local init_damage = damage
self.lastattacker = attacker
if self.inst.components.health and damage then
if self.inst.components.inventory then
damage = self.inst.components.inventory:ApplyDamage(damage, attacker)
end
if METRICS_ENABLED and GetPlayer() == self.inst then
local prefab = (attacker and (attacker.prefab or attacker.inst.prefab)) or "NIL"
ProfileStatsAdd("hitsby_"..prefab,math.floor(damage))
FightStat_AttackedBy(attacker,damage,init_damage-damage)
end
if damage > 0 and self.inst.components.health:IsInvincible() == false then
self.inst.components.health:DoDelta(-damage, nil, attacker and attacker.prefab or "NIL")
if self.inst.components.health:GetPercent() <= 0 then
if attacker then
attacker:PushEvent("killed", {victim = self.inst})
end
if METRICS_ENABLED and attacker and attacker == GetPlayer() then
ProfileStatsAdd("kill_"..self.inst.prefab)
FightStat_AddKill(self.inst,damage,weapon)
end
if METRICS_ENABLED and attacker and attacker.components.follower and attacker.components.follower.leader == GetPlayer() then
ProfileStatsAdd("kill_by_minion"..self.inst.prefab)
FightStat_AddKillByFollower(self.inst,damage,weapon)
end
if METRICS_ENABLED and attacker and attacker.components.mine then
ProfileStatsAdd("kill_by_trap_"..self.inst.prefab)
FightStat_AddKillByMine(self.inst,damage)
end
if self.onkilledbyother then
self.onkilledbyother(self.inst, attacker)
end
end
else
blocked = true
end
end
if self.inst.SoundEmitter then
local hitsound = self:GetImpactSound(self.inst, weapon)
if hitsound then
self.inst.SoundEmitter:PlaySound(hitsound)
--print (hitsound)
end
if self.hurtsound then
self.inst.SoundEmitter:PlaySound(self.hurtsound)
end
end
if not blocked then
self.inst:PushEvent("attacked", {attacker = attacker, damage = damage, weapon = weapon, stimuli = stimuli})
if self.onhitfn then
self.onhitfn(self.inst, attacker, damage)
end
if attacker then
attacker:PushEvent("onhitother", {target = self.inst, damage = damage, stimuli = stimuli})
if attacker.components.combat and attacker.components.combat.onhitotherfn then
attacker.components.combat.onhitotherfn(attacker, self.inst, damage, stimuli)
end
end
else
self.inst:PushEvent("blocked", {attacker = attacker})
end
return not blocked
end
function Combat:GetImpactSound(target, weapon)
if not target then
return
end
local hitsound = "dontstarve/impacts/impact_"
local specialtype = nil
if target.components.inventory and target.components.inventory:IsWearingArmor() then
if target.components.inventory:ArmorHasTag("grass") then
hitsound = hitsound.."straw_"
elseif target.components.inventory:ArmorHasTag("forcefield") then
hitsound = hitsound.."forcefield_"
elseif target.components.inventory:ArmorHasTag("sanity") then
hitsound = hitsound.."sanity_"
elseif target.components.inventory:ArmorHasTag("sanity") then
hitsound = hitsound.."sanity_"
elseif target.components.inventory:ArmorHasTag("marble") then
hitsound = hitsound.."marble_"
elseif target.components.inventory:ArmorHasTag("shell") then
hitsound = hitsound.."shell_"
elseif target.components.inventory:ArmorHasTag("fur") then
hitsound = hitsound.."fur_"
elseif target.components.inventory:ArmorHasTag("metal") then
hitsound = hitsound.."metal_"
else
hitsound = hitsound.."wood_"
end
specialtype = "armour"
elseif target:HasTag("wall") then
if target:HasTag("grass") then
hitsound = hitsound.."straw_"
elseif target:HasTag("stone") then
hitsound = hitsound.."stone_"
elseif target:HasTag("marble") then
hitsound = hitsound.."marble_"
else
hitsound = hitsound.."wood_"
end
specialtype = "wall"
elseif target:HasTag("object") then
if target:HasTag("clay") then
hitsound = hitsound.."clay_"
elseif target:HasTag("stone") then
hitsound = hitsound.."stone_"
end
specialtype = "object"
elseif target:HasTag("hive") or target:HasTag("eyeturret") or target:HasTag("houndmound") then
hitsound = hitsound.."hive_"
elseif target:HasTag("ghost") then
hitsound = hitsound.."ghost_"
elseif target:HasTag("insect") or target:HasTag("spider") then
hitsound = hitsound.."insect_"
elseif target:HasTag("chess") or target:HasTag("mech") then
hitsound = hitsound.."mech_"
elseif target:HasTag("mound") then
hitsound = hitsound.."mound_"
elseif target:HasTag("shadow") then
hitsound = hitsound.."shadow_"
elseif target:HasTag("tree") then
hitsound = hitsound.."tree_"
elseif target:HasTag("veggie") then
hitsound = hitsound.."vegetable_"
elseif target:HasTag("shell") then
hitsound = hitsound.."shell_"
elseif target:HasTag("rocky") then
hitsound = hitsound.."stone_"
else
hitsound = hitsound.."flesh_"
end
if specialtype then
hitsound = hitsound..specialtype.."_"
elseif target:HasTag("smallcreature") or target:HasTag("small") then
hitsound = hitsound.."sml_"
elseif target:HasTag("largecreature") or target:HasTag("epic") or target:HasTag("large") then
hitsound = hitsound.."lrg_"
elseif target:HasTag("wet") then
hitsound = hitsound.."wet_"
else
hitsound = hitsound.."med_"
end
if weapon and weapon:HasTag("sharp") then
hitsound = hitsound.."sharp"
else
hitsound = hitsound.."dull"
end
return hitsound
end
function Combat:StartAttack()
if self.target and self.forcefacing then
self.inst:ForceFacePoint(self.target:GetPosition())
end
self.laststartattacktime = GetTime()
end
function Combat:CanTarget(target)
return target and
(not self.panic_thresh or self.inst.components.health:GetPercent() >= self.panic_thresh) and
target.entity:IsValid() and
not target:IsInLimbo() and
target.components.combat and
not (target.sg and target.sg:HasStateTag("invisible")) and
target.components.health and
not target.components.health:IsDead()
and self.inst.components.combat:IsValidTarget(target)
and target.components.combat:CanBeAttacked(self.inst)
end
function Combat:CanAttack(target)
if not target then
return false
end
if not self.canattack then
return false
end
if self.laststartattacktime then
local time_since_doattack = GetTime() - self.laststartattacktime
if time_since_doattack < self.min_attack_period then
return false
end
end
if not self:IsValidTarget(target) then
return false
end
if self.inst.sg and self.inst.sg:HasStateTag("busy") then
return false
end
local tpos = Point(target.Transform:GetWorldPosition())
local pos = Point(self.inst.Transform:GetWorldPosition())
if distsq(tpos,pos) <= self:CalcAttackRangeSq(target) then
return true
else
return false
end
end
function Combat:TryAttack(target)
local target = target or self.target
local is_attacking = self.inst.sg:HasStateTag("attack")
if is_attacking then
return true
end
if self:CanAttack(target) then
self.inst:PushEvent("doattack", {target = target})
return true
end
return false
end
function Combat:ForceAttack()
if self.target and self:TryAttack() then
return true
else
self.inst:PushEvent("doattack")
end
end
function Combat:GetWeapon()
if self.inst.components.inventory then
local item = self.inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
if item and item.components.weapon then
return item
end
end
end
function Combat:CalcDamage(target, weapon, multiplier)
if target:HasTag("alwaysblock") then
return 0
end
local multiplier = multiplier or 1
if self.damagemultiplier then multiplier = multiplier * self.damagemultiplier end
local bonus = self.damagebonus or 0
if weapon then
local weapondamage = 0
if weapon.components.weapon.variedmodefn then
local d = weapon.components.weapon.variedmodefn(weapon)
weapondamage = d.damage
else
weapondamage = weapon.components.weapon.damage
end
if not weapondamage then weapondamage = 0 end
return weapondamage*multiplier + bonus
end
if target and target:HasTag("player") then
return self.defaultdamage * self.playerdamagepercent * multiplier + bonus
end
return self.defaultdamage * multiplier + bonus
end
function Combat:GetAttackRange()
local range = self.attackrange
local weapon = self:GetWeapon()
if weapon and weapon.components.weapon.variedmodefn then
local weaponrange = weapon.components.weapon.variedmodefn(weapon)
range = range + weaponrange.attackrange
elseif weapon and weapon.components.weapon.attackrange then
range = range + weapon.components.weapon.attackrange
end
return range
end
function Combat:CalcAttackRangeSq(target)
target = target or self.target
local range = self:GetAttackRange() + (target.Physics and target.Physics:GetRadius() or 0)
return range*range
end
function Combat:CanAttackTarget(targ, weapon)
if targ and targ:IsValid() and not targ:IsInLimbo() then
local rangesq = self:CalcAttackRangeSq(targ)
if targ.components.combat and self.inst:GetDistanceSqToInst(targ) <= rangesq then
return true
end
if weapon and weapon.components.projectile then
local range = weapon.components.projectile.hitdist + (targ.Physics and targ.Physics:GetRadius() or 0)
if weapon:GetDistanceSqToInst(targ) < range*range then
return true
end
end
end
end
function Combat:GetHitRange()
local range = self.hitrange
local weapon = self:GetWeapon()
if weapon and weapon.components.weapon.variedmodefn then
local weaponrange = weapon.components.weapon.variedmodefn(weapon)
range = range + weaponrange.hitrange
elseif weapon and weapon.components.weapon.hitrange then
range = range + weapon.components.weapon.hitrange
end
--print("GetHitRange", self.inst, self.hitrange, range)
return range
end
function Combat:CalcHitRangeSq(target)
target = target or self.target
local range = self:GetHitRange() + (target.Physics and target.Physics:GetRadius() or 0)
return range*range
end
function Combat:CanHitTarget(targ, weapon)
--print("CanHitTarget", self.inst)
local specialcase_target = false
if targ and targ.components.burnable and (targ.components.burnable:IsSmoldering() or targ.components.burnable:IsBurning())
and self:GetWeapon() and self:GetWeapon():HasTag("extinguisher") then
specialcase_target = true
end
if not specialcase_target and targ and targ.components.burnable and targ.components.burnable.canlight and not targ.components.burnable:IsBurning() and not targ:HasTag("burnt")
and self:GetWeapon() and self:GetWeapon():HasTag("rangedlighter") then
specialcase_target = true
end
if self.inst and self.inst:IsValid() and targ and targ:IsValid() and not targ:IsInLimbo() and (specialcase_target or (targ.components.combat and targ.components.combat:CanBeAttacked(self.inst))) then
local rangesq = self:CalcHitRangeSq(targ)
if (specialcase_target or targ.components.combat) and self.inst:GetDistanceSqToInst(targ) <= rangesq then
return true
end
if weapon and weapon.components.projectile then
local range = weapon.components.projectile.hitdist + (targ.Physics and targ.Physics:GetRadius() or 0)
if weapon:GetDistanceSqToInst(targ) < range*range then
return true
end
end
end
end
function Combat:CanAreaHitTarget(targ)
if self:IsValidTarget(targ) then
return true
end
end
function Combat:DoAttack(target_override, weapon, projectile, stimuli, instancemult)
local targ = target_override or self.target
local weapon = weapon or self:GetWeapon()
if self:CanHitTarget(targ, weapon) then
self.inst:PushEvent("onattackother", {target = targ, weapon = weapon, projectile = projectile, stimuli = stimuli})
if weapon and weapon.components.projectile and not projectile then
local projectile = self.inst.components.inventory:DropItem(weapon, false)
if projectile then
projectile.components.projectile:Throw(self.inst, targ)
end
elseif weapon and weapon.components.weapon:CanRangedAttack() and not projectile then
weapon.components.weapon:LaunchProjectile(self.inst, targ)
else
local mult = 1
if stimuli == "electric" or (weapon and weapon.components.weapon and weapon.components.weapon.stimuli == "electric") then
if not targ:HasTag("electricdamageimmune") and (not targ.components.inventory or (targ.components.inventory and not targ.components.inventory:IsInsulated())) then
mult = TUNING.ELECTRIC_DAMAGE_MULT
if targ.components.moisture then
mult = mult + (TUNING.ELECTRIC_WET_DAMAGE_MULT * targ.components.moisture:GetMoisturePercent())
elseif targ.components.moisturelistener and targ.components.moisturelistener:IsWet() then
mult = mult + TUNING.ELECTRIC_WET_DAMAGE_MULT
elseif GetWorld() and GetWorld().components.moisturemanager and GetWorld().components.moisturemanager:IsEntityWet(targ) then
mult = mult + TUNING.ELECTRIC_WET_DAMAGE_MULT
end
end
end
local damage = self:CalcDamage(targ, weapon, mult)
if instancemult then damage = damage * instancemult end
if targ.components.combat then targ.components.combat:GetAttacked(self.inst, damage, weapon, stimuli) end
if METRICS_ENABLED and self.inst:HasTag( "player" ) then
ProfileStatsAdd("hitson_"..targ.prefab,math.floor(damage))
FightStat_Attack(targ,weapon,projectile,damage)
end
if METRICS_ENABLED and self.inst.components.follower
and self.inst.components.follower.leader == GetPlayer() then
FightStat_AttackByFollower(targ,weapon,projectile,damage)
end
if weapon then
weapon.components.weapon:OnAttack(self.inst, targ, projectile)
end
if self.areahitrange then
self:DoAreaAttack(targ, self.areahitrange, weapon, nil, stimuli)
end
self.lastdoattacktime = GetTime()
end
else
self.inst:PushEvent("onmissother", {target = targ, weapon = weapon})
if self.areahitrange then
local epicentre = projectile or self.inst
self:DoAreaAttack(epicentre, self.areahitrange, weapon, nil, stimuli)
end
end
end
function Combat:DoAreaAttack(target, range, weapon, validfn, stimuli)
local hitcount = 0
local pt = Vector3(target.Transform:GetWorldPosition() )
local ents = TheSim:FindEntities(pt.x, pt.y, pt.z, range)
for i,ent in ipairs(ents) do
if ent.components.combat
and ent ~= target
and ent ~= self.inst
and self:CanAreaHitTarget(ent)
and (not validfn or validfn(ent)) then
self.inst:PushEvent("onareaattackother", {target = target, weapon = weapon, stimuli = stimuli})
ent.components.combat:GetAttacked(self.inst, self:CalcDamage(ent, weapon, self.areahitdamagepercent), weapon, stimuli)
hitcount = hitcount + 1
end
end
return hitcount
end
function Combat:IsAlly(guy)
return (guy == self.inst) or
(self.inst.components.leader and self.inst.components.leader:IsFollower(guy)) or
(guy.components.leader and guy.components.leader:IsFollower(self.inst)) or
(self.inst:HasTag("player") and guy:HasTag("companion"))
end
function Combat:CanBeAttacked(attacker)
local can_be_attacked = true
if self.canbeattackedfn then
can_be_attacked = self.canbeattackedfn(self.inst, attacker)
end
return can_be_attacked
end
function Combat:CollectSceneActions(doer, actions)
if doer:CanDoAction(ACTIONS.ATTACK) and not self.inst.components.health:IsDead() then
if self:CanBeAttacked(attacker) then
table.insert(actions, ACTIONS.ATTACK)
end
end
end
function Combat:OnSave()
if self.target then
return { target = self.target.GUID }, {self.target.GUID}
end
end
function Combat:LoadPostPass(newents, data)
if data.target then
local target = newents[data.target]
if target then
self:SetTarget(target.entity)
end
end
end
function Combat:OnRemoveFromEntity()
self.inst:RemoveTag("hascombatcomponent")
self.inst:RemoveTag("combat")
end
return Combat
| gpl-2.0 |
victorperin/tibia-server | data/npc/scripts/Gregor.lua | 1 | 5051 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function creatureSayCallback(cid, type, msg)
local player = Player(cid)
if not npcHandler:isFocused(cid) then
return false
elseif msgcontains(msg, "addon") or msgcontains(msg, "outfit") then
if player:getStorageValue(Storage.OutfitQuest.KnightHatAddon) < 1 then
npcHandler:say("Only the bravest warriors may wear adorned helmets. They are traditionally awarded after having completed a difficult {task} for our guild.", cid)
npcHandler.topic[cid] = 1
end
elseif msgcontains(msg, "Task") then
if npcHandler.topic[cid] == 1 then
npcHandler:say("You mean, you would like to prove that you deserve to wear such a helmet?", cid)
npcHandler.topic[cid] = 2
end
elseif msgcontains(msg, "fang") or msgcontains(msg, "behemoth") then
if player:getStorageValue(Storage.OutfitQuest.KnightHatAddon) == 1 then
npcHandler:say("Have you really managed to fulfil the task and brought me 100 perfect behemoth fangs?", cid)
npcHandler.topic[cid] = 4
end
elseif msgcontains(msg, "helmet") then
if player:getStorageValue(Storage.OutfitQuest.KnightHatAddon) == 2 then
npcHandler:say("Did you recover the helmet of Ramsay the Reckless?", cid)
npcHandler.topic[cid] = 5
end
elseif msgcontains(msg, "sweat") or msgcontains(msg, "flask") then
if player:getStorageValue(Storage.OutfitQuest.KnightHatAddon) == 3 then
npcHandler:say("Were you able to get hold of a flask with pure warrior's sweat?", cid)
npcHandler.topic[cid] = 6
end
elseif msgcontains(msg, "steel") then
if player:getStorageValue(Storage.OutfitQuest.KnightHatAddon) == 4 then
npcHandler:say("Ah, have you brought the royal steel?", cid)
npcHandler.topic[cid] = 7
end
elseif msgcontains(msg, "yes") then
if npcHandler.topic[cid] == 2 then
npcHandler:say({"Well then, listen closely. First, you will have to prove that you are a fierce and restless warrior by bringing me 100 perfect behemoth fangs. ...",
"Secondly, please retrieve a helmet for us which has been lost a long time ago. The famous Ramsay the Reckless wore it when exploring an ape settlement. ...",
"Third, we need a new flask of warrior's sweat. We've run out of it recently, but we need a small amount for the show battles in our arena. ...",
"Lastly, I will have our smith refine your helmet if you bring me royal steel, an especially noble metal. ...",
"Did you understand everything I told you and are willing to handle this task?"}, cid, 0, 1, 4000)
npcHandler.topic[cid] = 3
elseif npcHandler.topic[cid] == 3 then
npcHandler:say("Alright then. Come back to me once you have collected 100 perfect behemoth fangs.", cid)
player:setStorageValue(Storage.OutfitQuest.KnightHatAddon, 1)
player:setStorageValue(Storage.OutfitQuest.DefaultStart, 1) --this for default start of Outfit and Addon Quests
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 4 then
if player:getItemCount(5893) >= 100 then
npcHandler:say("I'm deeply impressed, (brave Knight) " .. player:getName() .. ". (Even if you are not a knight, you certainly possess knight qualities.) Now, please retrieve Ramsay's helmet.", cid)
player:removeItem(5893, 100)
player:setStorageValue(Storage.OutfitQuest.KnightHatAddon, 2)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 5 then
if player:getItemCount(5924) >= 1 then
npcHandler:say("Good work, (brave Knight) " .. player:getName() .. "! Even though it is damaged, it has a lot of sentimental value. Now, please bring me warrior's sweat.", cid)
player:removeItem(5924, 1)
player:setStorageValue(Storage.OutfitQuest.KnightHatAddon, 3)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 6 then
if player:getItemCount(5885) >= 1 then
npcHandler:say("Now that is a pleasant surprise, (brave Knight) " .. player:getName() .. "! There is only one task left now: Obtain royal steel to have your helmet refined.", cid)
player:removeItem(5885, 1)
player:setStorageValue(Storage.OutfitQuest.KnightHatAddon, 4)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 7 then
if player:getItemCount(5887) >= 1 then
npcHandler:say("You truly deserve to wear an adorned helmet, (brave Knight) " .. player:getName() .. ". Please talk to Sam and tell him I sent you. I'm sure he will be glad to refine your helmet.", cid)
player:removeItem(5887, 1)
player:setStorageValue(Storage.OutfitQuest.KnightHatAddon, 5)
npcHandler.topic[cid] = 0
end
end
end
return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| apache-2.0 |
iranddos/yagop | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
nimaghorbani/dozdi9 | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
omidtarh/fire | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
AmirFieBeR/Amir_FieBeR | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
AmirFieBeR/Amir_FieBeR | bot/bot.lua | 1 | 6651 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {226359893},
disabled_channels = {}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
czfshine/Don-t-Starve | data/DLC0001/scripts/speech_wathgrithr.lua | 1 | 40405 | return {
ACTIONFAIL =
{
SHAVE =
{
AWAKEBEEFALO = "Let him sleep. Then I'll prune him.",
GENERIC = "Unshaveworthy.",
NOBITS = "But there's nothing to trim!",
},
STORE =
{
GENERIC = "It's packed full.",
NOTALLOWED = "That's not a good spot for this.",
},
},
ACTIONFAIL_GENERIC = "It can't be done.",
ANNOUNCE_ADVENTUREFAIL = "Back to the Otherworld, victory shall be mine!",
ANNOUNCE_BEES = "Back wee speared creatures!",
ANNOUNCE_BOOMERANG = "Urg! I must master the curved weapon.",
ANNOUNCE_CHARLIE = "Show yourself!",
ANNOUNCE_CHARLIE_ATTACK = "Coward!",
ANNOUNCE_COLD = "Brrr! Where are my furs!",
ANNOUNCE_HOT = "The hot sun tires me.",
ANNOUNCE_CRAFTING_FAIL = "I lack the provisions.",
ANNOUNCE_DEERCLOPS = "A worthy foe approaches.",
ANNOUNCE_DUSK = "The sun is setting, darkness waits nearby.",
ANNOUNCE_EAT =
{
GENERIC = "Meat makes my heart sing!",
PAINFUL = "Ohh, I don't feel well.",
SPOILED = "Ugh, fresh is better.",
STALE = "That was stale beast.",
INVALID = "This is not food fit for a warrior.",
},
ANNOUNCE_ENTER_DARK = "And the curtain falls.",
ANNOUNCE_ENTER_LIGHT = "I step into the light!",
ANNOUNCE_FREEDOM = "Freedom! The saga continues!",
ANNOUNCE_HIGHRESEARCH = "I am an excellent craftswoman.",
ANNOUNCE_HOUNDS = "The beasts are approaching...",
ANNOUNCE_HUNGRY = "How I long for a feast!",
ANNOUNCE_HUNT_BEAST_NEARBY = "Keep quiet, the creature is near.",
ANNOUNCE_HUNT_LOST_TRAIL = "I've lost the tracks.",
ANNOUNCE_HUNT_LOST_TRAIL_SPRING = "It's too muddy for trailing.",
ANNOUNCE_INV_FULL = "I'm carrying all I can!",
ANNOUNCE_KNOCKEDOUT = "Ugh, my head.",
ANNOUNCE_LOWRESEARCH = "That wasn't very exciting.",
ANNOUNCE_MOSQUITOS = "Away tiny demons!",
ANNOUNCE_NODANGERSLEEP = "It's not safe to sleep. Use the spear!",
ANNOUNCE_NODAYSLEEP = "The sun is high, journey on!",
ANNOUNCE_NODAYSLEEP_CAVE = "I won't be resting yet.",
ANNOUNCE_NOHUNGERSLEEP = "I'll starve overnight! Feast first.",
ANNOUNCE_NOSLEEPONFIRE = "I won't sleep in the flames.",
ANNOUNCE_NODANGERSIESTA = "Battle is upon us, there'll be no rest!",
ANNOUNCE_NONIGHTSIESTA = "No napping in the moonlight.",
ANNOUNCE_NONIGHTSIESTA_CAVE = "This doesn't feel like the time for a nap.",
ANNOUNCE_NOHUNGERSIESTA = "I'd like a meat snack first.",
ANNOUNCE_NO_TRAP = "Thankfully, I am light of foot.",
ANNOUNCE_PECKED = "Away feisty beaker!",
ANNOUNCE_QUAKE = "The world shudders!",
ANNOUNCE_RESEARCH = "The power of research is great.",
ANNOUNCE_SHELTER = "Aha! Shelter!",
ANNOUNCE_THORNS = "Arg, I've been poked!",
ANNOUNCE_TORCH_OUT = "My light is quenched!",
ANNOUNCE_TRAP_WENT_OFF = "That wasn't part of the plan.",
ANNOUNCE_UNIMPLEMENTED = "It is not of this world.",
ANNOUNCE_WORMHOLE = "That was a sloppy adventure.",
ANNOUNCE_CANFIX = "\nI can repair this.",
ANNOUNCE_ACCOMPLISHMENT = "May I return to battle now?",
ANNOUNCE_ACCOMPLISHMENT_DONE = "Victory! All right, let's go.",
ANNOUNCE_INSUFFICIENTFERTILIZER = "More droppings for you?",
ANNOUNCE_TOOL_SLIP = "Slippery devil!",
ANNOUNCE_LIGHTNING_DAMAGE_AVOIDED = "I rode in on a bolt lightning.",
ANNOUNCE_DAMP = "Slick for battle.",
ANNOUNCE_WET = "I am a wet warrior.",
ANNOUNCE_WETTER = "Does this count as a bath?",
ANNOUNCE_SOAKED = "I'm nearly drowned!",
BATTLECRY =
{
GENERIC = "Valhalla awaits!",
PIG = "I'm having pig tonight!",
PREY = "Die bravely little foe!",
SPIDER = "Spider, meet my spear!",
SPIDER_WARRIOR = "Prepare to be slain!",
},
COMBAT_QUIT =
{
GENERIC = "Odin will have you yet!",
PIG = "I'll be back pigskin!",
PREY = "I let you go this time!",
SPIDER = "Leggy coward.",
SPIDER_WARRIOR = "Flee monster! I will return.",
},
DESCRIBE =
{
GLOMMER = "A majestic goober.",
GLOMMERFLOWER =
{
GENERIC = "A wonder of the woods.",
DEAD = "It was once a wonder of the woods.",
},
GLOMMERWINGS = "Ohh, look what goober left for me.",
GLOMMERFUEL = "This slop could be useful.",
BELL = "I prefer the ring of blades clashing.",
STATUEGLOMMER =
{
GENERIC = "A curious homage to the gods.",
EMPTY = "That wasn't very respectful of me.",
},
WEBBERSKULL = "He fought with boldness, but his burial will not be that of a viking.",
WORMLIGHT = "Glowing treasure, I can't resist!",
WORM =
{
PLANT = "I smell a trap.",
DIRT = "What's under that dirt?",
WORM = "A snake beast from the depths!",
},
MOLE =
{
HELD = "A friend for my pocket.",
UNDERGROUND = "Who's under there?",
ABOVEGROUND = "He digs without abandon.",
},
MOLEHILL = "Something lives down there.",
MOLEHAT = "I use every part of the animal.",
EEL = "Delicious slimy snake fish.",
EEL_COOKED = "Hot eel!",
UNAGI = "No need for food to be so fancy.",
EYETURRET = "The eye of the laser god stares at me.",
EYETURRET_ITEM = "An ancient eyeball of protection!",
MINOTAURHORN = "Can I add this to my helmet?",
MINOTAURCHEST = "The conquest chest!",
THULECITE_PIECES = "Looks like shiny popped corn.",
POND_ALGAE = "An ancient flora.",
GREENSTAFF = "Twirly green power.",
POTTEDFERN = "What am I supposed to do with this?",
THULECITE = "A strength of this material is gargantuan!",
ARMORRUINS = "Armour fit for Odin himself!",
RUINS_BAT = "A warrior wand!",
RUINSHAT = "A crown, that fights!",
NIGHTMARE_TIMEPIECE =
{
CALM = "Nothing stirs.",
WARN = "It's starting...",
WAXING = "The magic is heightening!",
STEADY = "The magic holds steady power.",
WANING = "It's starting to retreat!",
DAWN = "Barely any magic remains.",
NOMAGIC = "The magic slumbers far from here.",
},
BISHOP_NIGHTMARE = "Watch for his blasts!",
ROOK_NIGHTMARE = "You don't frighten me!",
KNIGHT_NIGHTMARE = "I don't think I'd ride that horse.",
MINOTAUR = "What wonders! Let's duel.",
SPIDER_DROPPER = "You are so sneaky!",
NIGHTMARELIGHT = "It harnesses the dark powers from beneath.",
NIGHTSTICK = "A weapon worthy of Thor.",
GREENGEM = "An emerald stone.",
RELIC = "Old bits of a dwelling.",
RUINS_RUBBLE = "I'm quite crafty, I could repair this.",
MULTITOOL_AXE_PICKAXE = "A warrior tool!",
ORANGESTAFF = "The staff of magic movement.",
YELLOWAMULET = "A star captured in an amulet.",
GREENAMULET = "Enhanced emerald crafting skills!",
SLURPERPELT = "I do love furs.",
SLURPER = "Fur foe thinks she's a hat!",
SLURPER_PELT = "I do love furs.",
ARMORSLURPER = "She ebbs my hunger. Good fur.",
ORANGEAMULET = "Gathering has never been so easy.",
YELLOWSTAFF = "It summons stars!",
YELLOWGEM = "A yellow beaut.",
ORANGEGEM = "A stone of orange.",
TELEBASE =
{
VALID = "Prepare for the power of purple.",
GEMS = "There's still gems missing.",
},
GEMSOCKET =
{
VALID = "Ready!",
GEMS = "It's empty.",
},
STAFFLIGHT = "Behold! A gift from Wotan!",
ANCIENT_ALTAR = "This crafts better be good.",
ANCIENT_ALTAR_BROKEN = "This one is not in working order.",
ANCIENT_STATUE = "Treasure with mysterious aura.",
LICHEN = "Sky blue nonsense plant.",
CUTLICHEN = "I picked it. But I won't eat it.",
CAVE_BANANA = "Monkey food.",
CAVE_BANANA_COOKED = "Warmed monkey food.",
CAVE_BANANA_TREE = "A flimsy monkey tree.",
ROCKY = "He may be a worthy combat comrade.",
COMPASS =
{
GENERIC="I can't get a reading.",
N = "North",
S = "South",
E = "East",
W = "West",
NE = "Northeast",
SE = "Southeast",
NW = "Northwest",
SW = "Southwest",
},
NIGHTMARE_TIMEPIECE =
{
WAXING = "The magic is heightening!",
STEADY = "The magic holds steady power.",
WANING = "It's starting to retreat!",
DAWN = "Barely any magic remains.",
WARN = "It's starting...",
CALM = "Nothing stirs.",
NOMAGIC = "The magic slumbers far from here.",
},
HOUNDSTOOTH="A token of my conquest.",
ARMORSNURTLESHELL="A shield of sorts.",
BAT="Dark winged meat.",
BATBAT = "Wing spear!",
BATWING="Like the wings of my helm, only meatier.",
BATWING_COOKED="Cooked dark wing.",
BEDROLL_FURRY="A luxury fur bed!",
BUNNYMAN="I want to eat you.",
FLOWER_CAVE="And it lit up the night, upon the darkest hour.",
FLOWER_CAVE_DOUBLE="And it lit up the night, upon the darkest hour.",
FLOWER_CAVE_TRIPLE="And it lit up the night, upon the darkest hour.",
GUANO="Hmm, dark wing turds.",
LANTERN="A lantern for the darkness.",
LIGHTBULB="Glow!",
MANRABBIT_TAIL="Can I put it in my hair?",
MUSHTREE_TALL ="What is this magic?",
MUSHTREE_MEDIUM="I do like its glow.",
MUSHTREE_SMALL ="I don't care for mushrooms.",
RABBITHOUSE=
{
GENERIC = "What am I to do with a carrot that big?",
BURNT = "Good riddance giant carrot.",
},
SLURTLE="You are angel. Of nasty.",
SLURTLE_SHELLPIECES="They're smashed up good.",
SLURTLEHAT="A new battle helm for my collection!",
SLURTLEHOLE="Not where I'd choose to hang my helm.",
SLURTLESLIME="Yes. Slime.",
SNURTLE="I like his helmet.",
SPIDER_HIDER="I'll smash you!",
SPIDER_SPITTER="This one's fiesty.",
SPIDERHOLE="Webbing, never a good sign.",
STALAGMITE="Cave boulder.",
STALAGMITE_FULL="Cave boulder.",
STALAGMITE_LOW="Cave boulder.",
STALAGMITE_MED="Cave boulder.",
STALAGMITE_TALL="A pointy rock of sorts.",
STALAGMITE_TALL_FULL="A pointy rock of sorts.",
STALAGMITE_TALL_LOW="A pointy rock of sorts.",
STALAGMITE_TALL_MED="A pointy rock of sorts.",
TURF_CARPETFLOOR = "It soaks up the blood of battle.",
TURF_CHECKERFLOOR = "Fancy floor.",
TURF_DIRT = "A piece of the battlefield.",
TURF_FOREST = "A piece of the battlefield.",
TURF_GRASS = "A piece of the battlefield.",
TURF_MARSH = "A piece of the battlefield.",
TURF_ROAD = "The road to battle leads wherever I choose.",
TURF_ROCKY = "A piece of the battlefield.",
TURF_SAVANNA = "A piece of the battlefield.",
TURF_WOODFLOOR = "Wooden flooring, a fine surface for mortal combat.",
TURF_CAVE="A piece of the battlefield.",
TURF_FUNGUS="A piece of the battlefield.",
TURF_SINKHOLE="A piece of the battlefield.",
TURF_UNDERROCK="A piece of the battlefield.",
TURF_MUD="A piece of the battlefield.",
POWCAKE = "What in the name of the unicorn is this?",
CAVE_ENTRANCE =
{
GENERIC="What treasures lie beneath?",
OPEN = "To the underworld!",
},
CAVE_EXIT = "Back to open skies!",
MAXWELLPHONOGRAPH = "A mechanical songstress.",
BOOMERANG = "For flinging at foes!",
PIGGUARD = "He's battle ready, I can tell.",
ABIGAIL = "A lady ghost.",
ADVENTURE_PORTAL = "Adventure is calling.",
AMULET = "It's red, and a fighter. Just like me!",
ANIMAL_TRACK = "Oh! I love a good hunt.",
ARMORGRASS = "Grass protection. That's not going to last long.",
ARMORMARBLE = "Near impenetrable!",
ARMORWOOD = "A borrowed tree vest.",
ARMOR_SANITY = "Strong, but I find my mind wanders...",
ASH =
{
GENERIC = "The flames' remains.",
REMAINS_GLOMMERFLOWER = "The flower must remain in its home world.",
REMAINS_EYE_BONE = "The eyebone could not pass to this world.",
REMAINS_THINGIE = "It's burnt. Gone.",
},
AXE = "To chop and destroy!",
BABYBEEFALO = "Mini beastie.",
BACKPACK = "A portable armoury.",
BACONEGGS = "Pig and eggs!",
BANDAGE = "To heal my battle wounds.",
BASALT = "A thousand mortals couldn't break through this stone.",
BATBAT = "Wing spear!",
BEARDHAIR = "Fur of the crazies.",
BEDROLL_STRAW = "A tool for my naps.",
BEARGER = "Beast or berserker?",
BEARGERVEST = "I am berserker!",
ICEPACK = "A backpack of the beast.",
BEARGER_FUR = "It fought bravely but I have claimed its hide.",
BEE =
{
GENERIC = "Wee warriors! I don't know if I like them.",
HELD = "Easy now!",
},
BEEBOX =
{
FULLHONEY = "It's a honey treasure trove!",
GENERIC = "A sweet box of wee warriors.",
NOHONEY = "Where's the honey?",
SOMEHONEY = "Some honey. Patience is needed.",
BURNT = "My hive is silent.",
},
BEEFALO =
{
FOLLOWER = "Come along beastie.",
GENERIC = "Ancient woollen beasts!",
NAKED = "Are you cold without your wools?",
SLEEPING = "Sounds like Aunt Hilda.",
},
BEEFALOHAT = "This is going to look good on me, I can tell.",
BEEFALOWOOL = "I do love woolly things.",
BEEHAT = "My bee helm, of course.",
BEEHIVE = "Always buzzing, always plotting.",
BEEMINE = "It sounds suspicious.",
BEEMINE_MAXWELL = "Watch your step!",
BERRIES = "Fruits. I don't like 'em.",
BERRIES_COOKED = "Warm red mush.",
BERRYBUSH =
{
BARREN = "Should I put some turds on it?",
WITHERED = "It's too hot to grow.",
GENERIC = "A fruit bush.",
PICKED = "The fruits have been snatched.",
},
BIFOOT = "Stompy foot.",
BIRDCAGE =
{
GENERIC = "A home for my ravens!",
OCCUPIED = "Are you having a nice time?",
SLEEPING = "Sweet dreams raven friend.",
},
BIRDTRAP = "I'm a cunning raven catcher!",
BIRD_EGG = "Eggy.",
BIRD_EGG_COOKED = "Hot egg.",
BISHOP = "This one needs a good smack.",
BLOWDART_FIRE = "Like the breath of a dragon.",
BLOWDART_SLEEP = "Goodnight to my foes.",
BLOWDART_PIPE = "Projectile weaponry!",
BLUEAMULET = "Cold jewellery.",
BLUEGEM = "An icy blue sapphire.",
BLUEPRINT = "Oh, a map! No, wait. That's wrong.",
BELL_BLUEPRINT = "Oh, a map! No, wait. That's wrong.",
BLUE_CAP = "Hmm, a blue one.",
BLUE_CAP_COOKED = "I still don't want to eat it.",
BLUE_MUSHROOM =
{
GENERIC = "It's mold, really.",
INGROUND = "Good, it's hiding.",
PICKED = "I hope it doesn't grow again.",
},
BOARDS = "Grandfather logs.",
BOAT = "Is that how I got here?",
BONESHARD = "Bits of my enemies.",
BONESTEW = "Delicious!",
BUGNET = "To snatch insects from the air.",
BUSHHAT = "For the hunt.",
BUTTER = "Butter. Might it be good on steak?",
BUTTERFLY =
{
GENERIC = "It is sort of nice.",
HELD = "Caught!",
},
BUTTERFLYMUFFIN = "Muffin, smuffin.",
BUTTERFLYWINGS = "A pretty souvenir.",
BUZZARD = "You and I, we meat feast together.",
CACTUS =
{
GENERIC = "It does have admirable armour.",
PICKED = "It will return.",
},
CACTUS_MEAT_COOKED = "Toasted sword plant meat.",
CACTUS_MEAT = "Sword plant meat.",
CACTUS_FLOWER = "Beauty from braun.",
COLDFIRE =
{
EMBERS = "That fire's nearly dead.",
GENERIC = "A cold comfort.",
HIGH = "The fire roars!",
LOW = "Fire's slowly dying.",
NORMAL = "A cold comfort.",
OUT = "And the light flickers out.",
},
CAMPFIRE =
{
EMBERS = "That fire's nearly dead.",
GENERIC = "Warm fire, warm Wigfrid.",
HIGH = "The fire roars!",
LOW = "Fire's slowly dying.",
NORMAL = "Warm fire, warm Wigfrid.",
OUT = "And the light flickers out.",
},
CANE = "Turns walk to trot.",
CATCOON = "Oh! Cute meat with fur.",
CATCOONDEN =
{
GENERIC = "Cute meat lives there.",
EMPTY = "She fought bravely. Alas, she is gone.",
},
CATCOONHAT = "Furry cap! Bless cute meat.",
COONTAIL = "It is the tail of cute meat.",
CARROT = "Where's the protein?",
CARROT_COOKED = "Sad cooked carrots.",
CARROT_PLANTED = "A wee root vegetable.",
CARROT_SEEDS = "Tiny nature bits.",
CAVE_FERN = "Foliage from the dark ages.",
CHARCOAL = "Loot from Loge the demigod.",
CHESSJUNK1 = "It's only a pile of fallen warriors.",
CHESSJUNK2 = "More fallen mechanical warriors.",
CHESSJUNK3 = "Someone should really clean this place up.",
CHESTER = "Don't worry, I won't eat him.",
CHESTER_EYEBONE =
{
GENERIC = "Who are you?",
WAITING = "The eyeball is tired.",
},
COOKEDMANDRAKE = "She's definitely dead.",
COOKEDMEAT = "Meeeat!",
COOKEDMONSTERMEAT = "Monster beast steak.",
COOKEDSMALLMEAT = "Yum, yum, meat snacks.",
COOKPOT =
{
COOKING_LONG = "Might as well do something while I wait.",
COOKING_SHORT = "Shouldn't be long now!",
DONE = "What have we got here?",
EMPTY = "Nothing in there.",
BURNT = "The fire reigned supreme.",
},
CORN = "A vegetable sword!",
CORN_COOKED = "Popped corn smells good.",
CORN_SEEDS = "Tiny nature bits.",
CROW =
{
GENERIC = "Raven friend!",
HELD = "Together again.",
},
CUTGRASS = "A craftwoman's most elemental resource.",
CUTREEDS = "I cleaned all the bugs out! Then I ate them.",
CUTSTONE = "Solid stone!",
DEADLYFEAST = "A most potent dish.",
DEERCLOPS = "Rays will shine through my spear and poke out your eyeball!",
DEERCLOPS_EYEBALL = "Hmm, shall I eat it?",
EYEBRELLAHAT = "Don't get rain in your eye!",
DEPLETED_GRASS =
{
GENERIC = "It's probably a tuft of grass.",
},
DEVTOOL = "It smells of bacon!",
DEVTOOL_NODEV = "I'm not strong enough to wield it.",
DIRTPILE = "A small hill of earth.",
DIVININGROD =
{
COLD = "All is quiet.",
GENERIC = "A mechanical hunting hound. For the hunt.",
HOT = "Sound the horns! We've arrived!",
WARM = "We've got the scent!",
WARMER = "The hound is excited, we're getting closer.",
},
DIVININGRODBASE =
{
GENERIC = "What cryptic ruins.",
READY = "Seems like I'm missing a piece...",
UNLOCKED = "Ready! The saga continues!",
},
DIVININGRODSTART = "This mysterious sword feels important.",
DRAGONFLY = "Ah dragon! We meet at last!",
ARMORDRAGONFLY = "Excellent armour for the heat of battle.",
DRAGON_SCALES = "Mystical scales.",
DRAGONFLYCHEST = "This chest is worthy of my weapons.",
LAVASPIT =
{
HOT = "Your fire pools are no match for me!",
COOL = "It's not very scary now, is it?",
},
DRAGONFRUIT = "It's very fancy.",
DRAGONFRUIT_COOKED = "Grilled fancy fruit.",
DRAGONFRUIT_SEEDS = "Tiny nature bits.",
DRAGONPIE = "Why isn't this a meat pie? Meat, meeeat!",
DRUMSTICK = "Leg of beastie, in my belly.",
DRUMSTICK_COOKED = "Hooooot meat!",
DUG_BERRYBUSH = "I think I'll return this to the earth goddess.",
DUG_GRASS = "I think I'll return this to the earth goddess.",
DUG_MARSH_BUSH = "I think I'll return this to the earth goddess.",
DUG_SAPLING = "I think I'll return this to the earth goddess.",
DURIAN = "Smells like my battle boots.",
DURIAN_COOKED = "Why did I cook this again?",
DURIAN_SEEDS = "Tiny nature bits.",
EARMUFFSHAT = "Yes, most practical!",
EGGPLANT = "Purpley and bulbous.",
EGGPLANT_COOKED = "Food for the weak.",
EGGPLANT_SEEDS = "Tiny nature bits.",
DECIDUOUSTREE =
{
BURNING = "The wood's ablaze!",
BURNT = "Loge took that one.",
CHOPPED = "Chopped by the warrior in the woods!",
POISON = "I've got to work a bit harder for this firewood.",
GENERIC = "Future firewood!",
},
ACORN =
{
GENERIC = "There's a tree hiding within.",
PLANTED = "Grow strong young twigs!",
},
ACORN_COOKED = "I cooked the young tree.",
BIRCHNUTDRAKE = "A young tree warrior!",
EVERGREEN =
{
BURNING = "The wood's ablaze!",
BURNT = "Loge took that one.",
CHOPPED = "Chopped by the warrior in the woods!",
GENERIC = "I feel at home in the woods.",
},
EVERGREEN_SPARSE =
{
BURNING = "The wood's ablaze!",
BURNT = "Loge took that one.",
CHOPPED = "Chopped by the warrior in the woods!",
GENERIC = "A good sturdy tree.",
},
EYEPLANT = "Don't point your eyeball at me foliage!",
FARMPLOT =
{
GENERIC = "I can't grow meat, what's the point?",
GROWING = "They're growing stronger.",
NEEDSFERTILIZER = "It wants a turd feast.",
BURNT = "Serves you right for not growing meats!",
},
FEATHERHAT = "Seems a bit flashy for battle.",
FEATHER_CROW = "A token from the ravens!",
FEATHER_ROBIN = "Red like my hair.",
FEATHER_ROBIN_WINTER = "Winter's feather.",
FEM_PUPPET = "She looks unhappy upon her throne.",
FIREFLIES =
{
GENERIC = "Tiny fairy lights aglow!",
HELD = "I hold the light!",
},
FIREHOUND = "The flamed one has no mercy.",
FIREPIT =
{
EMBERS = "That fire's nearly dead.",
GENERIC = "Warm fire, warm Wigfrid.",
HIGH = "The fire roars!",
LOW = "Fire's slowly dying.",
NORMAL = "Warm fire, warm Wigfrid.",
OUT = "And the light flickers out.",
},
COLDFIREPIT =
{
EMBERS = "That fire's nearly dead.",
GENERIC = "A cold comfort.",
HIGH = "The fire roars!",
LOW = "Fire's slowly dying.",
NORMAL = "A cold comfort.",
OUT = "And the light flickers out.",
},
FIRESTAFF = "Wigfrid! Master of fire!",
FIRESUPPRESSOR =
{
ON = "Catapult engaged for battle!",
OFF = "Time to rest flinging warrior.",
LOWFUEL = "The catapult grows weak and tired.",
},
FISH = "Meat of the sea!",
FISHINGROD = "I'm a ruthless fisherwoman.",
FISHSTICKS = "Spears of sea meat.",
FISHTACOS = "Fish in a blanket!",
FISH_COOKED = "Joy!",
FLINT = "Vital for spear construction.",
FLOWER = "A flower from Freia.",
FLOWERHAT = "Flimsy for the fight, pretty for my head.",
FLOWER_EVIL = "Some evil plagues this flora.",
FOLIAGE = "A collection of ferns.",
FOOTBALLHAT = "A pig's bottom made my helmet.",
FROG =
{
DEAD = "You're a bit slimy for Valhalla.",
GENERIC = "I'd like some frog boots someday.",
SLEEPING = "It sleeps.",
},
FROGGLEBUNWICH = "What a treat!",
FROGLEGS = "Filled with rubbery protein!",
FROGLEGS_COOKED = "I like when I can see the bones sticking out.",
FRUITMEDLEY = "Ugh! Putting it into a cup doesn't fool me.",
GEARS = "These might look nice glued to my helm.",
GHOST = "A spirit trapped between worlds.",
GOLDENAXE = "A tool of gold!",
GOLDENPICKAXE = "Gold for gold.",
GOLDENPITCHFORK = "Why did I even make a pitchfork this fancy?",
GOLDENSHOVEL = "Digging like a king!",
GOLDNUGGET = "I am pleased with this gold piece.",
GRASS =
{
BARREN = "The life has gone from it.",
WITHERED = "The heat has defeated this plant.",
BURNING = "Loge looks upon you!",
GENERIC = "That could be useful.",
PICKED = "It fell to my might.",
},
GREEN_CAP = "Terrible!",
GREEN_CAP_COOKED = "Charred by flame or not, it will not touch my lips!",
GREEN_MUSHROOM =
{
GENERIC = "It has risen!",
INGROUND = "Hide, coward.",
PICKED = "I see fungal spores.",
},
GUNPOWDER = "Such energy!",
HAMBAT = "A weapon fit for the great dining halls!",
HAMMER = "More fit for labour than battle.",
HEALINGSALVE = "Fill me with life!",
HEATROCK =
{
FROZEN = "Cold teeth bite at me!",
COLD = "The stone has taken on cold!",
GENERIC = "A stone of great use!",
WARM = "The stone has taken on warmth!",
HOT = "Loge would be proud.",
},
HOMESIGN =
{
GENERIC = "A most well placed sign.",
BURNT = "Signs of a battle past.",
},
HONEY = "Sticky and gross.",
HONEYCOMB = "Wouldn't make much of a comb.",
HONEYHAM = "A feast!",
HONEYNUGGETS = "A feast!",
HORN = "Makes me long for battle.",
HOUND = "Fenrir's spawn!",
HOUNDBONE = "A fallen foe.",
HOUNDMOUND = "These hounds are truly warriors.",
ICEBOX = "Winter dwells inside!",
ICEHAT = "A chunk of cold.",
ICEHOUND = "Teeth of frost!",
INSANITYROCK =
{
ACTIVE = "Woah!",
INACTIVE = "I suspect nothing of this rock.",
},
JAMMYPRESERVES = "Sticky and gross.",
KABOBS = "A feast!",
KILLERBEE =
{
GENERIC = "A challenger!",
HELD = "A conquered foe.",
},
KNIGHT = "I sense battle!",
KOALEFANT_SUMMER = "Dear creature, I am going to eat you.",
KOALEFANT_WINTER = "Poor unsuspecting meat beast.",
KRAMPUS = "You don't scare me goat!",
KRAMPUS_SACK = "I can fit everything in here!",
LEIF = "That's an ancient woodland being.",
LEIF_SPARSE = "That's an ancient woodland being.",
LIGHTNING_ROD =
{
CHARGED = "Oh great lightning!",
GENERIC = "Bring with you lightning Donner!",
},
LIGHTNINGGOAT =
{
GENERIC = "May I call you Unicorn?",
CHARGED = "The lightning has made you a unicorn warrior!",
},
LIGHTNINGGOATHORN = "This could deal a lasting blow.",
GOATMILK = "This is powerful milk.",
LITTLE_WALRUS = "A spawn of the evil toothed seal.",
LIVINGLOG = "Burning this magic would seem a waste.",
LOCKEDWES = "I'll save you silent mortal!",
LOG =
{
BURNING = "Flaming log!",
GENERIC = "Wood is always of value.",
},
LUREPLANT = "Finally! A useful vegetable.",
LUREPLANTBULB = "Perhaps I will be a meat farmer after all!",
MALE_PUPPET = "He looks unhappy upon his throne.",
MANDRAKE =
{
DEAD = "The corpse of the rutabaga still retains its magic.",
GENERIC = "A rutabaga!",
PICKED = "She just wants to go on a rutabaga saga.",
},
MANDRAKESOUP = "A stew of magic!",
MANDRAKE_COOKED = "Grilled rutabaga.",
MARBLE = "The warrior stone!",
MARBLEPILLAR = "Fit for a palace!",
MARBLETREE = "Even the winds won't knock this tree down.",
MARSH_BUSH =
{
BURNING = "Hot log!",
GENERIC = "A shrub on guard.",
PICKED = "What a nuisance.",
},
MARSH_PLANT = "Pond foliage.",
MARSH_TREE =
{
BURNING = "It's ablaze!",
BURNT = "Burnt.",
CHOPPED = "My battleaxe always wins.",
GENERIC = "A warrior tree.",
},
MAXWELL = "Arrg! Is that the antagonist to my saga?!",
MAXWELLHEAD = "I can see into his pores.",
MAXWELLLIGHT = "Dark magic lives here.",
MAXWELLLOCK = "Shall I unlock it?",
MAXWELLTHRONE = "I prefer to roam free, my unicorn and I.",
MEAT = "The true fruit of the earth!",
MEATBALLS = "Tiny feast balls.",
MEATRACK =
{
DONE = "Let's eat!",
DRYING = "It's preparing just the way I like it.",
DRYINGINRAIN = "All this rain isn't helping.",
GENERIC = "Ah! A dangly rack for my meats!",
BURNT = "Such a shame.",
},
MEAT_DRIED = "Excellent battle provisions.",
MERM = "Die soggy beast fish!",
MERMHEAD =
{
GENERIC = "I could smell it from back there!",
BURNT = "Beheaded. Burnt. Stinky.",
},
MERMHOUSE =
{
GENERIC = "Is this dwelling made of fish?",
BURNT = "I won't miss it.",
},
MINERHAT = "A lighted helm! For the darkness.",
MONKEY = "I don't trust him.",
MONKEYBARREL = "What's in the barrel?",
MONSTERLASAGNA = "Monster casserole.",
FLOWERSALAD = "Leaves are for animals.",
ICECREAM = "It hurts my teeth.",
WATERMELONICLE = "You cannot fool me by hiding in frozen fruit, stick.",
TRAILMIX = "Meat of a nut is not true meat.",
HOTCHILI = "A test of my willpower.",
GUACAMOLE = "Yum, creamy!",
MONSTERMEAT = "Meat of the dark beasts.",
MONSTERMEAT_DRIED = "All dried up.",
MOOSE = "I wish I could ride it into battle.",
MOOSEEGG = "Something is bouncing around inside.",
MOSSLING = "You are not large enough to be a steed.",
FEATHERFAN = "The luxuries of camp, on the go.",
GOOSE_FEATHER = "A shieldmaiden deserves a soft bed of dunn.",
STAFF_TORNADO = "A storm of pain.",
MOSQUITO =
{
GENERIC = "Ugh! These things are useless!",
HELD = "Settle demon fury!",
},
MOSQUITOSACK = "The blood will make me strong.",
MOUND =
{
DUG = "I wanted the loot!",
GENERIC = "Are there treasures beneath the gravestones?",
},
NIGHTLIGHT = "I'm more comfortable around my own fire.",
NIGHTMAREFUEL = "The fuel of darkness!",
NIGHTSWORD = "It takes a brave warrior to wield this sword.",
NITRE = "It contains explosive components.",
ONEMANBAND = "Sing with me! We are the guardians of Asgard!",
PANDORASCHEST = "It contains a mystery.",
PANFLUTE = "I prefer to face my enemies awake.",
PAPYRUS = "This will carry forth the record of my saga.",
PENGUIN = "Birds of the sea, come from afar.",
PERD = "You cannot run forever!",
PEROGIES = "Pockets of meat.",
PETALS = "Thank you Froh for this gift!",
PETALS_EVIL = "These were not made by Froh.",
PICKAXE = "I can use it to get precious spear and helm materials.",
PIGGYBACK = "The pig died with honor and gave to me this pack.",
PIGHEAD =
{
GENERIC = "This is savagery.",
BURNT = "Normally, I like a good roast, but this is not right.",
},
PIGHOUSE =
{
FULL = "Come out and go to war with me!",
GENERIC = "I did not think pigs could make houses.",
LIGHTSOUT = "Do you not hunger for battle, pig?",
BURNT = "Loge did not smile upon you this day.",
},
PIGKING = "Is it pig-Odin?",
PIGMAN =
{
DEAD = "He died with honor.",
FOLLOWER = "We ride to battle!",
GENERIC = "Will you fight alongside me, pig?",
GUARD = "That pig looks brave.",
WEREPIG = "It has been tainted by Fenrir.",
},
PIGSKIN = "The hide of a pig creature.",
PIGTORCH = "Do these pigs worship Loge?",
PINECONE =
{
GENERIC = "This baby tree is well protected by spiky armour.",
PLANTED = "It has shed its armour. Grow, baby tree!",
},
PITCHFORK = "A weapon for farmers.",
PLANTMEAT = "I suppose it's close enough.",
PLANTMEAT_COOKED = "Still green, but it'll do.",
PLANT_NORMAL =
{
GENERIC = "A plant.",
GROWING = "I am a shieldmaiden, not a farmer!",
READY = "Ugh, vegetables. I'm not sure what I expected...",
WITHERED = "Bested by the sun.",
},
POMEGRANATE = "Fruity flesh.",
POMEGRANATE_COOKED = "Seared fruit flesh.",
POMEGRANATE_SEEDS = "Tiny nature bits.",
POND = "Something lurks in the deep.",
POOP = "If only I could use it as camouflage from predators.",
FERTILIZER = "Its stench could raise the fallen.",
PUMPKIN = "It might make a good bludgeon, at least.",
PUMPKINCOOKIE = "Baked all the life out of it.",
PUMPKIN_COOKED = "Piping hot orange mush.",
PUMPKIN_LANTERN = "Do you wish to fight, vegetable?",
PUMPKIN_SEEDS = "Tiny nature bits.",
PURPLEAMULET = "An amulet of dark powers.",
PURPLEGEM = "It is cloudy with a mysterious energy.",
RABBIT =
{
GENERIC = "Jump into my mouth!",
HELD = "There is no escape!",
},
RABBITHOLE =
{
GENERIC = "Showtime, rabbits!",
SPRING = "It must be intermission for the rabbits.",
},
RAINOMETER =
{
GENERIC = "Foretells the coming of rain.",
BURNT = "Its prophecy days are done.",
},
RAINCOAT = "Armour for rain.",
RAINHAT = "We will fight in the rain.",
RATATOUILLE = "A pile of vegetables. No thanks.",
RAZOR = "A small blade, but a blade nonetheless.",
REDGEM = "It is hot to the touch.",
RED_CAP = "Umami or not, I don't want it.",
RED_CAP_COOKED = "I won't eat it, but it was fun to put in the fire.",
RED_MUSHROOM =
{
GENERIC = "At least it's got a nice colour.",
INGROUND = "And stay down there!",
PICKED = "Good riddance.",
},
REEDS =
{
BURNING = "See you in Asgard, reeds!",
GENERIC = "Those are some hardy reeds.",
PICKED = "Cut down in their prime.",
},
RELIC =
{
GENERIC = "Fit for Asgard.",
BROKEN = "It has been reduced to smithereens.",
},
RUINS_RUBBLE = "It's days are not done.",
RUBBLE = "A pile of ancient rocks.",
RESEARCHLAB =
{
GENERIC = "I prefer battle to science.",
BURNT = "Ashes to ashes.",
},
RESEARCHLAB2 =
{
GENERIC = "Perhaps science can enhance my combat skills.",
BURNT = "Dust to dust.",
},
RESEARCHLAB3 =
{
GENERIC = "A mystical thing.",
BURNT = "It's strange power did not protect it from fire.",
},
RESEARCHLAB4 =
{
GENERIC = "It is an absurd machine that makes meat.",
BURNT = "No more meat will come from here!",
},
RESURRECTIONSTATUE =
{
GENERIC = "I do not know why I made this.",
BURNT = "Valhalla, I come!",
},
RESURRECTIONSTONE = "It holds me back from Valhalla.",
ROBIN =
{
GENERIC = "Red like blood.",
HELD = "I prefer your black brethren.",
},
ROBIN_WINTER =
{
GENERIC = "This bird knows about the cold.",
HELD = "Such fluffy feathers.",
},
ROBOT_PUPPET = "A prisoner!",
ROCK_LIGHT =
{
GENERIC = "The lava crust is firm.",
OUT = "Looks delicate.",
LOW = "The lava crust is reforming.",
NORMAL = "Beautiful light!",
},
ROCK = "Smash!",
ROCK_ICE =
{
GENERIC = "A miniature frozen mountain.",
MELTED = "Poor glacier!",
},
ROCK_ICE_MELTED = "Poor glacier!",
ICE = "Reminds me of home.",
ROCKS = "Some pretty normal rocks.",
ROOK = "Chaaaarge!",
ROPE = "Strong enough to bind the sails of my longship.",
ROTTENEGG = "Ruined for eating, but primed for battle.",
SANITYROCK =
{
ACTIVE = "I do not think I can best this rock in combat.",
INACTIVE = "Clever rock, you cannot surprise a warrior!",
},
SAPLING =
{
BURNING = "Nooo! My spears!",
WITHERED = "It has been shriveled by the heat.",
GENERIC = "I will make it into a spear.",
PICKED = "I have slain the small tree!",
},
SEEDS = "Tiny nature bits.",
SEEDS_COOKED = "Tiny nature bits, cooked to death.",
SEWING_KIT = "I am no seamstress, but repairs are sometimes necessary.",
SHOVEL = "I'd prefer a ship burial, but it might have use.",
SILK = "Useful for binding and for remembering victories past.",
SKELETON = "Rest easy in Valhalla.",
SKELETON_PLAYER = "This fight is not yet over.",
SKULLCHEST = "Ah, that was a good battle.",
SMALLBIRD =
{
GENERIC = "You are not fierce yet, bird.",
HUNGRY = "You must eat to grow strong.",
STARVING = "The small bird looks famished.",
},
SMALLMEAT = "A nice meaty snack.",
SMALLMEAT_DRIED = "A small provision for a long campaign.",
SPEAR = "It is not my favoured spear, but it will do the trick.",
SPIDER =
{
DEAD = "Felled by my spear, like so many before it.",
GENERIC = "Eight legs and still no match for me!",
SLEEPING = "I will allow it a fair fight and wait 'til it wakes.",
},
SPIDERDEN = "Crush them at the source!",
SPIDEREGGSACK = "I could squash these but I'd miss out on more battles.",
SPIDERGLAND = "Ripped from the abdomen of a slain spider.",
SPIDERHAT = "A perfect way to infiltrate the enemy camp.",
SPIDERQUEEN = "Finally, a true test of my abilities.",
SPIDER_WARRIOR =
{
DEAD = "Victory for Wigfrid once again!",
GENERIC = "The champion of the spiders. To battle!",
SLEEPING = "It is cowardly to attack a sleeping enemy.",
},
SPOILED_FOOD = "Age has only made this food gross, not more wise.",
STATUEHARP = "It must be Gunnar. The snakes took his head.",
STATUEMAXWELL = "Fie, demon!",
STINGER = "The sword on the back of a bee.",
STRAWHAT = "A hat for cooling after a raucous battle.",
STUFFEDEGGPLANT = "Filling the vegetable does not make it meat.",
SUNKBOAT = "No wonder it sank. It is not a longship.",
SWEATERVEST = "It is a handsome vest but it offers no protection.",
REFLECTIVEVEST = "Ha! The sun is no warrior if it cannot penetrate this.",
HAWAIIANSHIRT = "Flowers will not stop a spear.",
TAFFY = "Long will the saga of this taffy be told.",
TALLBIRD = "Fearsome bird! But I am not afraid.",
TALLBIRDEGG = "It will grow into a formidable foe.",
TALLBIRDEGG_COOKED = "It was you or me, bird.",
TALLBIRDEGG_CRACKED =
{
COLD = "This egg would not survive a Norse winter.",
GENERIC = "Fight your way out, bird!",
HOT = "Borne of flame! Unless it cooks.",
LONG = "A while remains before this bird is born.",
SHORT = "Soon it will wake into this world.",
},
TALLBIRDNEST =
{
GENERIC = "A feathered warrior lurks inside.",
PICKED = "A young bird of war will be born soon.",
},
TEENBIRD =
{
GENERIC = "You are not yet ready for battle, bird.",
HUNGRY = "I hope you like vegetables--the meat is for me.",
STARVING = "To enter battle with me is your choice, bird.",
},
TELEBASE =
{
VALID = "It will harness my awesome speed.",
GEMS = "It requires purple gems.",
},
GEMSOCKET =
{
VALID = "Showtime!",
GEMS = "It lacks its gem.",
},
TELEPORTATO_BASE =
{
ACTIVE = "To Asgard!",
GENERIC = "A bridge to another world.",
LOCKED = "The bridge is unstable yet.",
PARTIAL = "The bridge is incomplete.",
},
TELEPORTATO_BOX = "Perhaps this holds the secret to this land's Bifrost.",
TELEPORTATO_CRANK = "A sturdy crank.",
TELEPORTATO_POTATO = "No decency. It's not even metal meat.",
TELEPORTATO_RING = "It appears similar to the Bifrost.",
TELESTAFF = "I ride through the air and the sea!",
TENT =
{
GENERIC = "Sleep this night, and prepare for battle on the morrow.",
BURNT = "It has been razed.",
},
SIESTAHUT =
{
GENERIC = "A place to rest my battle-weary head.",
BURNT = "It has been razed.",
},
TENTACLE = "It looks fierce. Into the fray!",
TENTACLESPIKE = "Gooey, but dangerous. I like it.",
TENTACLESPOTS = "A tough hide.",
TENTACLE_PILLAR = "A towering tentacle foe.",
TENTACLE_PILLAR_ARM = "A gross grasping appendage.",
TENTACLE_GARDEN = "I will thrust my spear into that mass of tentacles!",
TOPHAT = "It doesn't match my costume.",
TORCH = "Perfect for a nighttime assault.",
TRANSISTOR = "A marvel of science.",
TRAP = "A well constructed trap. I will have my meal.",
TRAP_TEETH = "A treacherous trap.",
TRAP_TEETH_MAXWELL = "An excellent mace wasted, buried in the ground.",
TREASURECHEST =
{
GENERIC = "A place to store my helm and spear while I rest.",
BURNT = "It's walls were torn down by fire.",
},
TREASURECHEST_TRAP = "I am always ready.",
TREECLUMP = "A dead end! I must stand and fight.",
TRINKET_1 = "Toys do not interest a great warrior such as I.",
TRINKET_10 = "A token of victory.",
TRINKET_11 = "A warrior encased in a fine armour.",
TRINKET_12 = "Shorn from a hideous monster.",
TRINKET_2 = "Accompaniment for the song of my triumphs.",
TRINKET_3 = "Even my spear cannot undo this knot.",
TRINKET_4 = "A peculiar small man.",
TRINKET_5 = "Will it take me to Asgard?",
TRINKET_6 = "Useless technology.",
TRINKET_7 = "No time for games! There is battle at hand!",
TRINKET_8 = "It would make an okay weapon in a pinch.",
TRINKET_9 = "No decent armour can be made with these.",
TRUNKVEST_SUMMER = "It will not suffice in the frozen wastes.",
TRUNKVEST_WINTER = "The warm pelt of a bested creature. A fine garment.",
TRUNK_COOKED = "A juicy reward after a hard battle.",
TRUNK_SUMMER = "A powerful trunk of a fallen not-so-hairy beast.",
TRUNK_WINTER = "A powerful trunk of a fallen hairy beast.",
TUMBLEWEED = "Flee, bouncing coward!",
TURKEYDINNER = "A true feast.",
TWIGS = "Good for making spears.",
UMBRELLA = "Rain protection made from the trophy of a hunt.",
GRASS_UMBRELLA = "I dislike flowers, but I dislike wet armour more.",
UNIMPLEMENTED = "A mysterious relic, sure to contain great power.",
WAFFLES = "Waffles are no way to prepare for battle!",
WALL_HAY =
{
GENERIC = "A minor deterrent to attackers.",
BURNT = "That won't do at all.",
},
WALL_HAY_ITEM = "Perhaps my foes will get lost in this hay.",
WALL_STONE = "My enemies will dash themselves on these rocks.",
WALL_STONE_ITEM = "A sturdy wall fashioned from the earth.",
WALL_RUINS = "Nigh impenetrable.",
WALL_RUINS_ITEM = "Only the finest barriers for my fort.",
WALL_WOOD =
{
GENERIC = "It may impale a foe.",
BURNT = "Fire, wood's only weakness!",
},
WALL_WOOD_ITEM = "A mediocre fortification.",
WALRUS = "Those tusks could pierce even the finest armour.",
WALRUSHAT = "Highland filth!",
WALRUS_CAMP =
{
EMPTY = "They have departed for a great journey.",
GENERIC = "A proper winter camp.",
},
WALRUS_TUSK = "Rended from the mouth of the sea beast.",
WARG = "Is it you, Fenrir?",
WASPHIVE = "Bees of war!",
WATERMELON = "It makes a good sound when you hit it.",
WATERMELON_COOKED = "Warm and red, but it doesn't flow.",
WATERMELONHAT = "It's almost like wearing a pelt.",
WETGOOP = "Slop.",
WINTERHAT = "Warm, but not suitable for combat.",
WINTEROMETER =
{
GENERIC = "If only it measured the heat of battle.",
BURNT = "The measuring device has been slain by Loge.",
},
WORMHOLE =
{
GENERIC = "Does it swallow those fallen in battle?",
OPEN = "It's maw welcomes me.",
},
WORMHOLE_LIMITED = "It is sickly and weak.",
ACCOMPLISHMENT_SHRINE = "My victories shall be remembered!",
LIVINGTREE = "A tree of life, but it is not Yggdrasil.",
ICESTAFF = "A gift from Ullr!",
WATHGRITHRHAT = "The power of the unicorn is great.",
SPEAR_WATHGRITHR = "My comrade in arms!",
},
DESCRIBE_GENERIC = "It is an artifact of this realm.",
DESCRIBE_TOODARK = "Too dark even for battle.",
DESCRIBE_SMOLDERING = "Flames will soon consume it.",
EAT_FOOD =
{
TALLBIRDEGG_CRACKED = "Bones and all.",
},
} | gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/debugsounds.lua | 1 | 5986 | require("class")
require("util")
--tweakable parameters
local maxRecentSounds = 30 --max number of recent sounds to list in the debug output
local maxDistance = 30 --max distance to show
local playsound = SoundEmitter.PlaySound
local killsound = SoundEmitter.KillSound
local killallsounds = SoundEmitter.KillAllSounds
local setparameter = SoundEmitter.SetParameter
local setvolume = SoundEmitter.SetVolume
local setlistener = Sim.SetListener
local nearbySounds = {}
local loopingSounds = {}
local soundCount = 0
local listenerPos = nil
TheSim:LoadPrefabs({"sounddebugicon"})
SoundEmitter.PlaySound = function(emitter, event, name, volume, ...)
local ent = emitter:GetEntity()
if ent and ent.Transform and listenerPos then
local pos = Vector3(ent.Transform:GetWorldPosition() )
local dist = math.sqrt(distsq(pos, listenerPos) )
if dist < maxDistance or name then
local soundIcon = nil
if name and loopingSounds[ent] and loopingSounds[ent][name] then
soundIcon = loopingSounds[ent][name].icon
else
soundIcon = SpawnPrefab("sounddebugicon")
end
if soundIcon then
soundIcon.Transform:SetPosition(pos:Get() )
end
local soundInfo = {event=event, owner=ent, guid=ent.GUID, prefab=ent.prefab or "", position=pos, dist=dist, volume=volume or 1, icon=soundIcon}
if name then
--add to looping sounds list
soundInfo.params = {}
if not loopingSounds[ent] then
loopingSounds[ent] = {}
end
loopingSounds[ent][name] = soundInfo
if soundIcon then
if soundIcon.autokilltask then
soundIcon.autokilltask:Cancel()
soundIcon.autokilltask = nil
end
soundIcon.Label:SetText(name)
end
else
--add to oneshot sound list
soundCount = soundCount + 1
local index = (soundCount % maxRecentSounds)+1
soundInfo.count = soundCount
nearbySounds[index] = soundInfo
if soundIcon then
soundIcon.Label:SetText(tostring(soundCount) )
end
end
end
end
playsound(emitter, event, name, volume, ...)
end
SoundEmitter.KillSound = function(emitter, name, ...)
local ent = emitter:GetEntity()
if loopingSounds[ent] then
if loopingSounds[ent][name] and loopingSounds[ent][name].icon then
loopingSounds[ent][name].icon:Remove()
end
loopingSounds[ent][name] = nil
end
killsound(emitter, name, ...)
end
SoundEmitter.KillAllSounds = function(emitter, ...)
local sounds = loopingSounds[emitter:GetEntity()]
if sounds then
for k,v in pairs(sounds) do
if v.icon then
v.icon:Remove()
end
sounds[v] = nil
end
sounds = nil
end
killallsounds(emitter, ...)
end
SoundEmitter.SetParameter = function(emitter, name, parameter, value, ...)
local ent = emitter:GetEntity()
if loopingSounds[ent] and loopingSounds[ent][name] then
loopingSounds[ent][name].params[name] = value
end
setparameter(emitter, name, parameter, value, ...)
end
SoundEmitter.SetVolume = function(emitter, name, volume, ...)
local ent = emitter:GetEntity()
if loopingSounds[ent] and loopingSounds[ent][name] then
loopingSounds[ent][name].volume = volume
end
setvolume(emitter, name, volume, ...)
end
Sim.SetListener = function(sim, x, y, z, ...)
listenerPos = Vector3(x, y, z)
setlistener(sim, x, y, z, ...)
end
local function DoUpdate()
for ent,sounds in pairs(loopingSounds) do
if not next(sounds) then
loopingSounds[ent] = nil
else
for name,info in pairs(sounds) do
if not ent:IsValid() or not ent.SoundEmitter or not ent.SoundEmitter:PlayingSound(name) then
if info.icon then
info.icon:Remove()
end
sounds[name] = nil
else
local pos = Vector3(ent.Transform:GetWorldPosition() )
local dist = math.sqrt(distsq(pos, listenerPos) )
info.dist = dist
info.pos = pos
if info.icon then
info.icon.Transform:SetPosition(pos:Get() )
end
end
end
end
end
end
scheduler:ExecutePeriodic(1, DoUpdate)
function GetSoundDebugString()
local lines = {}
table.insert(lines, "-------SOUND DEBUG-------")
table.insert(lines, "Looping Sounds")
for ent,sounds in pairs(loopingSounds) do
for name,info in pairs(sounds) do
if info.dist < maxDistance then
local params = ""
for k,v in pairs(info.params) do
params = params.." "..k.."="..v
end
table.insert(lines, string.format("[%s] %s owner:%d %s pos:%s dist:%2.2f volume:%d params:{%s}",
name, info.event, info.guid, info.prefab, tostring(info.pos), info.dist, info.volume, params) )
end
end
end
table.insert(lines, "Recent Sounds")
for i = soundCount-maxRecentSounds+1, soundCount do
local index = (i % maxRecentSounds)+1
if nearbySounds[index] then
local soundInfo = nearbySounds[index]
table.insert(lines, string.format("[%d] %s owner:%d %s pos:%s dist:%2.2f volume:%d",
soundInfo.count, soundInfo.event, soundInfo.guid, soundInfo.prefab, tostring(soundInfo.pos), soundInfo.dist, soundInfo.volume) )
end
end
return table.concat(lines, "\n")
end | gpl-2.0 |
liamgh/liamgreenhughes-sl4a-tf101 | lua/luasocket/src/socket.lua | 146 | 4061 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
module("socket")
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function connect(address, port, laddress, lport)
local sock, err = socket.tcp()
if not sock then return nil, err end
if laddress then
local res, err = sock:bind(laddress, lport, -1)
if not res then return nil, err end
end
local res, err = sock:connect(address, port)
if not res then return nil, err end
return sock
end
function bind(host, port, backlog)
local sock, err = socket.tcp()
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
end
try = newtry()
function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
sourcet = {}
sinkt = {}
BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
sink = choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
source = choose(sourcet)
| apache-2.0 |
nimaghorbani/nimabotv2 | plugins/banhammer.lua | 214 | 11956 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
local bots_protection = "Yes"
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = ''
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if member_id == our_id then return false end
if get_cmd == 'kick' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
return unbanall_user(member_id, chat_id)
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
local receiver = get_receiver(msg)
if matches[1]:lower() == 'kickme' then-- /kickme
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return nil
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'ban'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
return
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unban'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'kick'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'banall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unbanall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
timroes/awesome | lib/beautiful/theme_assets.lua | 2 | 8063 | ----------------------------------------------------------------------------
--- Generate vector assets using current colors.
--
-- @author Yauhen Kirylau <yawghen@gmail.com>
-- @copyright 2015 Yauhen Kirylau
-- @module beautiful.theme_assets
----------------------------------------------------------------------------
local cairo = require("lgi").cairo
local gears_color = require("gears.color")
local recolor_image = gears_color.recolor_image
local screen = screen
local theme_assets = {}
--- Generate selected taglist square.
-- @tparam number size Size.
-- @tparam color fg Background color.
-- @return Image with the square.
function theme_assets.taglist_squares_sel(size, fg)
local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size)
local cr = cairo.Context(img)
cr:set_source(gears_color(fg))
cr:paint()
return img
end
--- Generate unselected taglist square.
-- @tparam number size Size.
-- @tparam color fg Background color.
-- @return Image with the square.
function theme_assets.taglist_squares_unsel(size, fg)
local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size)
local cr = cairo.Context(img)
cr:set_source(gears_color(fg))
cr:set_line_width(size/4)
cr:rectangle(0, 0, size, size)
cr:stroke()
return img
end
local function make_letter(cr, n, lines, size, bg, fg, alt_fg)
local letter_gap = size/6
local function make_line(coords)
for i, coord in ipairs(coords) do
if i == 1 then
cr:rel_move_to(coord[1], coord[2])
else
cr:rel_line_to(coord[1], coord[2])
end
end
cr:stroke()
end
lines = lines or {}
local color = alt_fg or fg
cr:set_source(gears_color(color))
cr:rectangle(
0, (size+letter_gap)*n,
size, size
)
cr:fill()
if bg then
cr:set_source(gears_color(bg))
else
cr:set_operator(cairo.Operator.CLEAR)
end
for _, line in ipairs(lines) do
cr:move_to(0, (size+letter_gap)*n)
make_line(line)
end
cr:set_operator(cairo.Operator.OVER)
end
--- Put Awesome WM name onto cairo surface.
-- @param cr Cairo surface.
-- @tparam number height Height.
-- @tparam color bg Background color.
-- @tparam color fg Main foreground color.
-- @tparam color alt_fg Accent foreground color.
function theme_assets.gen_awesome_name(cr, height, bg, fg, alt_fg)
local ls = height/10 -- letter_size
local letter_line = ls/18
cr:set_line_width(letter_line)
-- a
make_letter(cr, 0, { {
{ 0, ls/3 },
{ ls*2/3, 0 },
}, {
{ ls/3, ls*2/3 },
{ ls/3, 0 },
{ 0, ls/3 },
} }, ls, bg, fg, alt_fg)
-- w
make_letter(cr, 1, { {
{ ls/3, 0 },
{ 0,ls*2/3 },
}, {
{ ls*2/3, 0 },
{ 0,ls*2/3 },
} }, ls, bg, fg)
-- e
make_letter(cr, 2, { {
{ ls/3, ls/3 },
{ ls*2/3, 0 },
}, {
{ ls/3, ls*2/3 },
{ ls*2/3, 0 },
} }, ls, bg, fg)
-- s
make_letter(cr, 3, { {
{ ls/3, ls/3 },
{ ls*2/3, 0 },
}, {
{ 0, ls*2/3 },
{ ls*2/3, 0 },
} }, ls, bg, fg)
-- o
make_letter(cr, 4, { {
{ ls/2, ls/3 },
{ 0, ls/3 },
} }, ls, bg, fg)
-- m
make_letter(cr, 5, { {
{ ls/3, ls/3 },
{ 0,ls*2/3 },
}, {
{ ls*2/3, ls/3 },
{ 0,ls*2/3 },
} }, ls, bg, fg)
-- e
make_letter(cr, 6, { {
{ ls/3, ls/3 },
{ ls*2/3, 0 },
}, {
{ ls/3, ls*2/3 },
{ ls*2/3, 0 },
} }, ls, bg, fg)
end
--- Put Awesome WM logo onto cairo surface.
-- @param cr Cairo surface.
-- @tparam number width Width.
-- @tparam number height Height.
-- @tparam color bg Background color.
-- @tparam color fg Foreground color.
function theme_assets.gen_logo(cr, width, height, bg, fg)
local ls = math.min(width, height)
local letter_line = ls/18
cr:set_line_width(letter_line)
make_letter(cr, 0, { {
{ 0, ls/3 },
{ ls*2/3, 0 },
}, {
{ ls/3, ls*2/3 },
{ ls/3, 0 },
{ 0, ls/3 },
} }, ls, bg, fg)
end
--- Generate Awesome WM logo.
-- @tparam number size Size.
-- @tparam color bg Background color.
-- @tparam color fg Background color.
-- @return Image with the logo.
function theme_assets.awesome_icon(size, bg, fg)
local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size)
local cr = cairo.Context(img)
theme_assets.gen_logo(cr, size, size, fg, bg)
return img
end
--- Generate Awesome WM wallpaper.
-- @tparam color bg Background color.
-- @tparam color fg Main foreground color.
-- @tparam color alt_fg Accent foreground color.
-- @tparam screen s Screen (to get wallpaper size).
-- @return Wallpaper image.
function theme_assets.wallpaper(bg, fg, alt_fg, s)
s = s or screen.primary
local height = s.geometry.height
local width = s.geometry.width
local img = cairo.RecordingSurface(cairo.Content.COLOR,
cairo.Rectangle { x = 0, y = 0, width = width, height = height })
local cr = cairo.Context(img)
local letter_start_x = width - width / 10
local letter_start_y = height / 10
cr:translate(letter_start_x, letter_start_y)
-- background
cr:set_source(gears_color(bg))
cr:paint()
theme_assets.gen_awesome_name(cr, height, bg, fg, alt_fg)
return img
end
--- Recolor unfocused titlebar icons.
-- @tparam table theme Beautiful theme table
-- @tparam color color Icons' color.
-- @treturn table Beautiful theme table with the images recolored.
function theme_assets.recolor_titlebar_normal(theme, color)
for _, titlebar_icon in ipairs({
'titlebar_close_button_normal',
'titlebar_minimize_button_normal',
'titlebar_ontop_button_normal_inactive',
'titlebar_ontop_button_normal_active',
'titlebar_sticky_button_normal_inactive',
'titlebar_sticky_button_normal_active',
'titlebar_floating_button_normal_inactive',
'titlebar_floating_button_normal_active',
'titlebar_maximized_button_normal_inactive',
'titlebar_maximized_button_normal_active',
}) do
theme[titlebar_icon] = recolor_image(theme[titlebar_icon], color)
end
return theme
end
--- Recolor focused titlebar icons.
-- @tparam table theme Beautiful theme table
-- @tparam color color Icons' color.
-- @treturn table Beautiful theme table with the images recolored.
function theme_assets.recolor_titlebar_focus(theme, color)
for _, titlebar_icon in ipairs({
'titlebar_close_button_focus',
'titlebar_minimize_button_focus',
'titlebar_ontop_button_focus_inactive',
'titlebar_ontop_button_focus_active',
'titlebar_sticky_button_focus_inactive',
'titlebar_sticky_button_focus_active',
'titlebar_floating_button_focus_inactive',
'titlebar_floating_button_focus_active',
'titlebar_maximized_button_focus_inactive',
'titlebar_maximized_button_focus_active',
}) do
theme[titlebar_icon] = recolor_image(theme[titlebar_icon], color)
end
return theme
end
--- Recolor layout icons.
-- @tparam table theme Beautiful theme table
-- @tparam color color Icons' color.
-- @treturn table Beautiful theme table with the images recolored.
function theme_assets.recolor_layout(theme, color)
for _, layout_name in ipairs({
'layout_fairh',
'layout_fairv',
'layout_floating',
'layout_magnifier',
'layout_max',
'layout_fullscreen',
'layout_tilebottom',
'layout_tileleft',
'layout_tile',
'layout_tiletop',
'layout_spiral',
'layout_dwindle',
'layout_cornernw',
'layout_cornerne',
'layout_cornersw',
'layout_cornerse',
}) do
theme[layout_name] = recolor_image(theme[layout_name], color)
end
return theme
end
return theme_assets
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
victorperin/tibia-server | data/npc/scripts/A Dead Bureaucrat2.lua | 1 | 1605 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function greetCallback(cid)
if Player(cid):getStorageValue(Storage.pitsOfInferno.Pumin) == 4 then
npcHandler:say("Hey! You are back! How can I help you this time?", cid)
npcHandler.topic[cid] = 1
else
npcHandler:setMessage(MESSAGE_GREET, "Hello " .. (Player(cid):getSex() == 0 and "beautiful lady" or "handsome gentleman") .. ", welcome to the atrium of Pumin's Domain. We require some information from you before we can let you pass. Where do you want to go?")
end
return true
end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
if msgcontains(msg, "287") then
if npcHandler.topic[cid] == 1 then
Player(cid):setStorageValue(Storage.pitsOfInferno.Pumin, 5)
npcHandler:say("Sure, you can get it from me. Here you are. Bye", cid)
end
npcHandler.topic[cid] = 0
end
return true
end
npcHandler:setMessage(MESSAGE_WALKAWAY, "Good bye and don't forget me!")
npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye and don't forget me!")
npcHandler:setCallback(CALLBACK_GREET, greetCallback)
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| apache-2.0 |
CrazyEddieTK/Zero-K | LuaUI/Widgets/gui_selectkeys.lua | 2 | 6526 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Select Keys",
desc = "v0.035 Common SelectKey Hotkeys for EPIC Menu.",
author = "CarRepairer",
date = "2010-09-23",
license = "GNU GPL, v2 or later",
layer = 1002,
enabled = true,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--[[
Note:
The selection actions in this file must match those in luaui/configs/zk_keys.lua
Please keep them up to date.
--]]
--------------------------------------------------------------------------------
options_path = 'Hotkeys/Selection'
options_order = {
'lbl_visibilty',
'select_all_visible',
'select_landw',
'selectairw',
'lbl_same',
'select_same',
'select_same_except_builder',
'select_vissame',
'lbl_filter',
'select_half',
'select_one',
'select_nonidle',
'select_idle',
'select_constructor',
'select_non_constructor',
'lowhealth_30',
'highhealth_30',
'lowhealth_60',
'highhealth_60',
'lowhealth_100',
'highhealth_100',
'lbl_w',
'select_all',
'uikey1',
'uikey2',
'uikey3',
'uikey4',
'uikey5',
'uikey6',
}
options = {
lbl_filter = { type = 'label', name = 'Filters'},
lbl_visibilty = { type = 'label', name = 'On Screen'},
lbl_same = { type = 'label', name = 'By Type In Selection' },
lbl_w = { type = 'label', name = 'Global Selection' },
select_all = { type = 'button',
name = 'All Units',
desc = 'Select all units.',
action = 'select AllMap++_ClearSelection_SelectAll+',
},
select_all_visible = { type = 'button',
name = 'All Visible Units',
desc = 'Select all visibleunits.',
action = 'select Visible++_ClearSelection_SelectAll+',
},
select_landw = { type = 'button',
name = 'Visible Armed Land',
desc = 'Select all visible armed land units.',
action = 'select Visible+_Not_Builder_Not_Building_Not_Aircraft_Weapons+_ClearSelection_SelectAll+',
},
selectairw = { type = 'button',
name = 'Visible Armed Flying',
desc = 'Select all visible armed flying units.',
action = 'select Visible+_Not_Building_Not_Transport_Aircraft_Weapons+_ClearSelection_SelectAll+',
},
select_vissame = { type = 'button',
name = 'Visible Same',
desc = 'Select all visible units of the same type as current selection.',
action = 'select Visible+_InPrevSel+_ClearSelection_SelectAll+',
},
select_same_except_builder = { type = 'button',
name = 'All Same Except Builders',
desc = 'Deselects builders then selects all units of the same type as current selection.',
action = 'select AllMap+_InPrevSel_Not_Builder+_ClearSelection_SelectAll+',
},
select_same = { type = 'button',
name = 'All Same',
desc = 'Select all units of the same type as current selection.',
action = 'select AllMap+_InPrevSel+_ClearSelection_SelectAll+',
},
select_half = { type = 'button',
name = 'Deselect Half',
desc = 'Deselect half of the selected units.',
action = 'select PrevSelection++_ClearSelection_SelectPart_50+',
},
select_one = { type = 'button',
name = 'Deselect Except One',
desc = 'Deselect all but one of the selected units.',
action = 'select PrevSelection++_ClearSelection_SelectOne+',
},
select_nonidle = { type = 'button',
name = 'Deselect non-idle',
desc = 'Deselect all but the idle selected units.',
action = 'select PrevSelection+_Idle+_ClearSelection_SelectAll+',
},
select_idle = { type = 'button',
name = 'Deselect idle',
desc = 'Deselect all idle selected units.',
action = 'select PrevSelection+_Not_Idle+_ClearSelection_SelectAll+',
},
select_constructor = { type = 'button',
name = 'Deselect constructor',
desc = 'Deselect all constructors.',
action = 'select PrevSelection+_Not_Builder+_ClearSelection_SelectAll+',
},
select_non_constructor = { type = 'button',
name = 'Deselect non-constructor',
desc = 'Deselect all non-constructors.',
action = 'select PrevSelection+_Builder+_ClearSelection_SelectAll+',
},
lowhealth_30 = { type = 'button',
name = 'Deselect Above 30% Health',
desc = 'Filters high health units out of your selection.',
action = 'select PrevSelection+_Not_RelativeHealth_30+_ClearSelection_SelectAll+',
},
highhealth_30 = { type = 'button',
name = 'Deselect Below 30% Health',
desc = 'Filters low health units out of your selection',
action = 'select PrevSelection+_RelativeHealth_30+_ClearSelection_SelectAll+',
},
lowhealth_60 = { type = 'button',
name = 'Deselect Above 60% Health',
desc = 'Filters high health units out of your selection.',
action = 'select PrevSelection+_Not_RelativeHealth_60+_ClearSelection_SelectAll+',
},
highhealth_60 = { type = 'button',
name = 'Deselect Below 60% Health',
desc = 'Filters low health units out of your selection',
action = 'select PrevSelection+_RelativeHealth_60+_ClearSelection_SelectAll+',
},
lowhealth_100 = { type = 'button',
name = 'Deselect Full Health',
desc = 'Filters full health units out of your selection',
action = 'select PrevSelection+_RelativeHealth_100+_ClearSelection_SelectAll+',
},
highhealth_100 = { type = 'button',
name = 'Deselect Damaged Units',
desc = 'Filters damaged units out of your selection',
action = 'select PrevSelection+_Not_RelativeHealth_100+_ClearSelection_SelectAll+',
},
----
uikey1 = { type = 'button',
name = 'Non-transport non-Raptor armed air',
desc = '',
action = 'select AllMap+_Not_Builder_Not_Building_Not_Transport_Aircraft_Weapons_Not_NameContain_Raptor_Not_Radar+_ClearSelection_SelectAll+',
},
uikey2 = { type = 'button',
name = 'Raptors',
desc = '',
action = 'select AllMap+_NameContain_Raptor+_ClearSelection_SelectAll+',
},
uikey3 = { type = 'button',
name = 'Mobile non-builders',
desc = '',
action = 'select AllMap+_Not_Builder_Not_Building+_ClearSelection_SelectAll+',
},
uikey4 = { type = 'button',
name = 'Owls',
desc = '',
action = 'select AllMap+_Not_Builder_Not_Building_Not_Transport_Aircraft_Radar+_ClearSelection_SelectAll+',
},
uikey5 = { type = 'button',
name = 'Air transports',
desc = '',
action = 'select AllMap+_Not_Builder_Not_Building_Transport_Aircraft+_ClearSelection_SelectAll+',
},
uikey6 = { type = 'button',
name = 'Append non-ctrl grouped',
desc = '',
action = 'select AllMap+_InPrevSel_Not_InHotkeyGroup+_SelectAll+',
},
}
| gpl-2.0 |
libnano/primer3-py | primer3/src/libprimer3/klib/lua/klib.lua | 42 | 20155 | --[[
The MIT License
Copyright (c) 2011, Attractive Chaos <attractor@live.co.uk>
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.
]]--
--[[
This is a Lua library, more exactly a collection of Lua snippets, covering
utilities (e.g. getopt), string operations (e.g. split), statistics (e.g.
Fisher's exact test), special functions (e.g. logarithm gamma) and matrix
operations (e.g. Gauss-Jordan elimination). The routines are designed to be
as independent as possible, such that one can copy-paste relevant pieces of
code without worrying about additional library dependencies.
If you use routines from this library, please include the licensing
information above where appropriate.
]]--
--[[
Library functions and dependencies. "a>b" means "a is required by b"; "b<a"
means "b depends on a".
os.getopt()
string:split()
io.xopen()
table.ksmall()
table.shuffle()
math.lgamma() >math.lbinom() >math.igamma()
math.igamma() <math.lgamma() >matrix.chi2()
math.erfc()
math.lbinom() <math.lgamma() >math.fisher_exact()
math.bernstein_poly() <math.lbinom()
math.fisher_exact() <math.lbinom()
math.jackknife()
math.pearson()
math.spearman()
math.fmin()
matrix
matrix.add()
matrix.T() >matrix.mul()
matrix.mul() <matrix.T()
matrix.tostring()
matrix.chi2() <math.igamma()
matrix.solve()
]]--
-- Description: getopt() translated from the BSD getopt(); compatible with the default Unix getopt()
--[[ Example:
for o, a in os.getopt(arg, 'a:b') do
print(o, a)
end
]]--
function os.getopt(args, ostr)
local arg, place = nil, 0;
return function ()
if place == 0 then -- update scanning pointer
place = 1
if #args == 0 or args[1]:sub(1, 1) ~= '-' then place = 0; return nil end
if #args[1] >= 2 then
place = place + 1
if args[1]:sub(2, 2) == '-' then -- found "--"
place = 0
table.remove(args, 1);
return nil;
end
end
end
local optopt = args[1]:sub(place, place);
place = place + 1;
local oli = ostr:find(optopt);
if optopt == ':' or oli == nil then -- unknown option
if optopt == '-' then return nil end
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
return '?';
end
oli = oli + 1;
if ostr:sub(oli, oli) ~= ':' then -- do not need argument
arg = nil;
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
else -- need an argument
if place <= #args[1] then -- no white space
arg = args[1]:sub(place);
else
table.remove(args, 1);
if #args == 0 then -- an option requiring argument is the last one
place = 0;
if ostr:sub(1, 1) == ':' then return ':' end
return '?';
else arg = args[1] end
end
table.remove(args, 1);
place = 0;
end
return optopt, arg;
end
end
-- Description: string split
function string:split(sep, n)
local a, start = {}, 1;
sep = sep or "%s+";
repeat
local b, e = self:find(sep, start);
if b == nil then
table.insert(a, self:sub(start));
break
end
a[#a+1] = self:sub(start, b - 1);
start = e + 1;
if n and #a == n then
table.insert(a, self:sub(start));
break
end
until start > #self;
return a;
end
-- Description: smart file open
function io.xopen(fn, mode)
mode = mode or 'r';
if fn == nil then return io.stdin;
elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout;
elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w');
elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w');
else return io.open(fn, mode) end
end
-- Description: find the k-th smallest element in an array (Ref. http://ndevilla.free.fr/median/)
function table.ksmall(arr, k)
local low, high = 1, #arr;
while true do
if high <= low then return arr[k] end
if high == low + 1 then
if arr[high] < arr[low] then arr[high], arr[low] = arr[low], arr[high] end;
return arr[k];
end
local mid = math.floor((high + low) / 2);
if arr[high] < arr[mid] then arr[mid], arr[high] = arr[high], arr[mid] end
if arr[high] < arr[low] then arr[low], arr[high] = arr[high], arr[low] end
if arr[low] < arr[mid] then arr[low], arr[mid] = arr[mid], arr[low] end
arr[mid], arr[low+1] = arr[low+1], arr[mid];
local ll, hh = low + 1, high;
while true do
repeat ll = ll + 1 until arr[ll] >= arr[low]
repeat hh = hh - 1 until arr[low] >= arr[hh]
if hh < ll then break end
arr[ll], arr[hh] = arr[hh], arr[ll];
end
arr[low], arr[hh] = arr[hh], arr[low];
if hh <= k then low = ll end
if hh >= k then high = hh - 1 end
end
end
-- Description: shuffle/permutate an array
function table.shuffle(a)
for i = #a, 1, -1 do
local j = math.random(i)
a[j], a[i] = a[i], a[j]
end
end
--
-- Mathematics
--
-- Description: log gamma function
-- Required by: math.lbinom()
-- Reference: AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245
function math.lgamma(z)
local x;
x = 0.1659470187408462e-06 / (z+7);
x = x + 0.9934937113930748e-05 / (z+6);
x = x - 0.1385710331296526 / (z+5);
x = x + 12.50734324009056 / (z+4);
x = x - 176.6150291498386 / (z+3);
x = x + 771.3234287757674 / (z+2);
x = x - 1259.139216722289 / (z+1);
x = x + 676.5203681218835 / z;
x = x + 0.9999999999995183;
return math.log(x) - 5.58106146679532777 - z + (z-0.5) * math.log(z+6.5);
end
-- Description: regularized incomplete gamma function
-- Dependent on: math.lgamma()
--[[
Formulas are taken from Wiki, with additional input from Numerical
Recipes in C (for modified Lentz's algorithm) and AS245
(http://lib.stat.cmu.edu/apstat/245).
A good online calculator is available at:
http://www.danielsoper.com/statcalc/calc23.aspx
It calculates upper incomplete gamma function, which equals
math.igamma(s,z,true)*math.exp(math.lgamma(s))
]]--
function math.igamma(s, z, complement)
local function _kf_gammap(s, z)
local sum, x = 1, 1;
for k = 1, 100 do
x = x * z / (s + k);
sum = sum + x;
if x / sum < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s + 1.) + math.log(sum));
end
local function _kf_gammaq(s, z)
local C, D, f, TINY;
f = 1. + z - s; C = f; D = 0.; TINY = 1e-290;
-- Modified Lentz's algorithm for computing continued fraction. See Numerical Recipes in C, 2nd edition, section 5.2
for j = 1, 100 do
local d;
local a, b = j * (s - j), j*2 + 1 + z - s;
D = b + a * D;
if D < TINY then D = TINY end
C = b + a / C;
if C < TINY then C = TINY end
D = 1. / D;
d = C * D;
f = f * d;
if math.abs(d - 1) < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s) - math.log(f));
end
if complement then
return ((z <= 1 or z < s) and 1 - _kf_gammap(s, z)) or _kf_gammaq(s, z);
else
return ((z <= 1 or z < s) and _kf_gammap(s, z)) or (1 - _kf_gammaq(s, z));
end
end
math.M_SQRT2 = 1.41421356237309504880 -- sqrt(2)
math.M_SQRT1_2 = 0.70710678118654752440 -- 1/sqrt(2)
-- Description: complement error function erfc(x): \Phi(x) = 0.5 * erfc(-x/M_SQRT2)
function math.erfc(x)
local z = math.abs(x) * math.M_SQRT2
if z > 37 then return (x > 0 and 0) or 2 end
local expntl = math.exp(-0.5 * z * z)
local p
if z < 10. / math.M_SQRT2 then -- for small z
p = expntl * ((((((.03526249659989109 * z + .7003830644436881) * z + 6.37396220353165) * z + 33.912866078383)
* z + 112.0792914978709) * z + 221.2135961699311) * z + 220.2068679123761)
/ (((((((.08838834764831844 * z + 1.755667163182642) * z + 16.06417757920695) * z + 86.78073220294608)
* z + 296.5642487796737) * z + 637.3336333788311) * z + 793.8265125199484) * z + 440.4137358247522);
else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))) end
return (x > 0 and 2 * p) or 2 * (1 - p)
end
-- Description: log binomial coefficient
-- Dependent on: math.lgamma()
-- Required by: math.fisher_exact()
function math.lbinom(n, m)
if m == nil then
local a = {};
a[0], a[n] = 0, 0;
local t = math.lgamma(n+1);
for m = 1, n-1 do a[m] = t - math.lgamma(m+1) - math.lgamma(n-m+1) end
return a;
else return math.lgamma(n+1) - math.lgamma(m+1) - math.lgamma(n-m+1) end
end
-- Description: Berstein polynomials (mainly for Bezier curves)
-- Dependent on: math.lbinom()
-- Note: to compute derivative: let beta_new[i]=beta[i+1]-beta[i]
function math.bernstein_poly(beta)
local n = #beta - 1;
local lbc = math.lbinom(n); -- log binomial coefficients
return function (t)
assert(t >= 0 and t <= 1);
if t == 0 then return beta[1] end
if t == 1 then return beta[n+1] end
local sum, logt, logt1 = 0, math.log(t), math.log(1-t);
for i = 0, n do sum = sum + beta[i+1] * math.exp(lbc[i] + i * logt + (n-i) * logt1) end
return sum;
end
end
-- Description: Fisher's exact test
-- Dependent on: math.lbinom()
-- Return: left-, right- and two-tail P-values
--[[
Fisher's exact test for 2x2 congintency tables:
n11 n12 | n1_
n21 n22 | n2_
-----------+----
n_1 n_2 | n
Reference: http://www.langsrud.com/fisher.htm
]]--
function math.fisher_exact(n11, n12, n21, n22)
local aux; -- keep the states of n* for acceleration
-- Description: hypergeometric function
local function hypergeo(n11, n1_, n_1, n)
return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
end
-- Description: incremental hypergeometric function
-- Note: aux = {n11, n1_, n_1, n, p}
local function hypergeo_inc(n11, n1_, n_1, n)
if n1_ ~= 0 or n_1 ~= 0 or n ~= 0 then
aux = {n11, n1_, n_1, n, 1};
else -- then only n11 is changed
local mod;
_, mod = math.modf(n11 / 11);
if mod ~= 0 and n11 + aux[4] - aux[2] - aux[3] ~= 0 then
if n11 == aux[1] + 1 then -- increase by 1
aux[5] = aux[5] * (aux[2] - aux[1]) / n11 * (aux[3] - aux[1]) / (n11 + aux[4] - aux[2] - aux[3]);
aux[1] = n11;
return aux[5];
end
if n11 == aux[1] - 1 then -- descrease by 1
aux[5] = aux[5] * aux[1] / (aux[2] - n11) * (aux[1] + aux[4] - aux[2] - aux[3]) / (aux[3] - n11);
aux[1] = n11;
return aux[5];
end
end
aux[1] = n11;
end
aux[5] = hypergeo(aux[1], aux[2], aux[3], aux[4]);
return aux[5];
end
-- Description: computing the P-value by Fisher's exact test
local max, min, left, right, n1_, n_1, n, two, p, q, i, j;
n1_, n_1, n = n11 + n12, n11 + n21, n11 + n12 + n21 + n22;
max = (n_1 < n1_ and n_1) or n1_; -- max n11, for the right tail
min = n1_ + n_1 - n;
if min < 0 then min = 0 end -- min n11, for the left tail
two, left, right = 1, 1, 1;
if min == max then return 1 end -- no need to do test
q = hypergeo_inc(n11, n1_, n_1, n); -- the probability of the current table
-- left tail
i, left, p = min + 1, 0, hypergeo_inc(min, 0, 0, 0);
while p < 0.99999999 * q do
left, p, i = left + p, hypergeo_inc(i, 0, 0, 0), i + 1;
end
i = i - 1;
if p < 1.00000001 * q then left = left + p;
else i = i - 1 end
-- right tail
j, right, p = max - 1, 0, hypergeo_inc(max, 0, 0, 0);
while p < 0.99999999 * q do
right, p, j = right + p, hypergeo_inc(j, 0, 0, 0), j - 1;
end
j = j + 1;
if p < 1.00000001 * q then right = right + p;
else j = j + 1 end
-- two-tail
two = left + right;
if two > 1 then two = 1 end
-- adjust left and right
if math.abs(i - n11) < math.abs(j - n11) then right = 1 - left + q;
else left = 1 - right + q end
return left, right, two;
end
-- Description: Delete-m Jackknife
--[[
Given g groups of values with a statistics estimated from m[i] samples in
i-th group being t[i], compute the mean and the variance. t0 below is the
estimate from all samples. Reference:
Busing et al. (1999) Delete-m Jackknife for unequal m. Statistics and Computing, 9:3-8.
]]--
function math.jackknife(g, m, t, t0)
local h, n, sum = {}, 0, 0;
for j = 1, g do n = n + m[j] end
if t0 == nil then -- When t0 is absent, estimate it in a naive way
t0 = 0;
for j = 1, g do t0 = t0 + m[j] * t[j] end
t0 = t0 / n;
end
local mean, var = 0, 0;
for j = 1, g do
h[j] = n / m[j];
mean = mean + (1 - m[j] / n) * t[j];
end
mean = g * t0 - mean; -- Eq. (8)
for j = 1, g do
local x = h[j] * t0 - (h[j] - 1) * t[j] - mean;
var = var + 1 / (h[j] - 1) * x * x;
end
var = var / g;
return mean, var;
end
-- Description: Pearson correlation coefficient
-- Input: a is an n*2 table
function math.pearson(a)
-- compute the mean
local x1, y1 = 0, 0
for _, v in pairs(a) do
x1, y1 = x1 + v[1], y1 + v[2]
end
-- compute the coefficient
x1, y1 = x1 / #a, y1 / #a
local x2, y2, xy = 0, 0, 0
for _, v in pairs(a) do
local tx, ty = v[1] - x1, v[2] - y1
xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty
end
return xy / math.sqrt(x2) / math.sqrt(y2)
end
-- Description: Spearman correlation coefficient
function math.spearman(a)
local function aux_func(t) -- auxiliary function
return (t == 1 and 0) or (t*t - 1) * t / 12
end
for _, v in pairs(a) do v.r = {} end
local T, S = {}, {}
-- compute the rank
for k = 1, 2 do
table.sort(a, function(u,v) return u[k]<v[k] end)
local same = 1
T[k] = 0
for i = 2, #a + 1 do
if i <= #a and a[i-1][k] == a[i][k] then same = same + 1
else
local rank = (i-1) * 2 - same + 1
for j = i - same, i - 1 do a[j].r[k] = rank end
if same > 1 then T[k], same = T[k] + aux_func(same), 1 end
end
end
S[k] = aux_func(#a) - T[k]
end
-- compute the coefficient
local sum = 0
for _, v in pairs(a) do -- TODO: use nested loops to reduce loss of precision
local t = (v.r[1] - v.r[2]) / 2
sum = sum + t * t
end
return (S[1] + S[2] - sum) / 2 / math.sqrt(S[1] * S[2])
end
-- Description: Hooke-Jeeves derivative-free optimization
function math.fmin(func, x, data, r, eps, max_calls)
local n, n_calls = #x, 0;
r = r or 0.5;
eps = eps or 1e-7;
max_calls = max_calls or 50000
function fmin_aux(x1, data, fx1, dx) -- auxiliary function
local ftmp;
for k = 1, n do
x1[k] = x1[k] + dx[k];
local ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp;
else -- search the opposite direction
dx[k] = -dx[k];
x1[k] = x1[k] + dx[k] + dx[k];
ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp
else x1[k] = x1[k] - dx[k] end -- back to the original x[k]
end
end
return fx1; -- here: fx1=f(n,x1)
end
local dx, x1 = {}, {};
for k = 1, n do -- initial directions, based on MGJ
dx[k] = math.abs(x[k]) * r;
if dx[k] == 0 then dx[k] = r end;
end
local radius = r;
local fx1, fx;
fx = func(x, data); fx1 = fx; n_calls = n_calls + 1;
while true do
for i = 1, n do x1[i] = x[i] end; -- x1 = x
fx1 = fmin_aux(x1, data, fx, dx);
while fx1 < fx do
for k = 1, n do
local t = x[k];
dx[k] = (x1[k] > x[k] and math.abs(dx[k])) or -math.abs(dx[k]);
x[k] = x1[k];
x1[k] = x1[k] + x1[k] - t;
end
fx = fx1;
if n_calls >= max_calls then break end
fx1 = func(x1, data); n_calls = n_calls + 1;
fx1 = fmin_aux(x1, data, fx1, dx);
if fx1 >= fx then break end
local kk = n;
for k = 1, n do
if math.abs(x1[k] - x[k]) > .5 * math.abs(dx[k]) then
kk = k;
break;
end
end
if kk == n then break end
end
if radius >= eps then
if n_calls >= max_calls then break end
radius = radius * r;
for k = 1, n do dx[k] = dx[k] * r end
else break end
end
return fx1, n_calls;
end
--
-- Matrix
--
matrix = {}
-- Description: matrix transpose
-- Required by: matrix.mul()
function matrix.T(a)
local m, n, x = #a, #a[1], {};
for i = 1, n do
x[i] = {};
for j = 1, m do x[i][j] = a[j][i] end
end
return x;
end
-- Description: matrix add
function matrix.add(a, b)
assert(#a == #b and #a[1] == #b[1]);
local m, n, x = #a, #a[1], {};
for i = 1, m do
x[i] = {};
local ai, bi, xi = a[i], b[i], x[i];
for j = 1, n do xi[j] = ai[j] + bi[j] end
end
return x;
end
-- Description: matrix mul
-- Dependent on: matrix.T()
-- Note: much slower without transpose
function matrix.mul(a, b)
assert(#a[1] == #b);
local m, n, p, x = #a, #a[1], #b[1], {};
local c = matrix.T(b); -- transpose for efficiency
for i = 1, m do
x[i] = {}
local xi = x[i];
for j = 1, p do
local sum, ai, cj = 0, a[i], c[j];
for k = 1, n do sum = sum + ai[k] * cj[k] end
xi[j] = sum;
end
end
return x;
end
-- Description: matrix print
function matrix.tostring(a)
local z = {};
for i = 1, #a do
z[i] = table.concat(a[i], "\t");
end
return table.concat(z, "\n");
end
-- Description: chi^2 test for contingency tables
-- Dependent on: math.igamma()
function matrix.chi2(a)
if #a == 2 and #a[1] == 2 then -- 2x2 table
local x, z
x = (a[1][1] + a[1][2]) * (a[2][1] + a[2][2]) * (a[1][1] + a[2][1]) * (a[1][2] + a[2][2])
if x == 0 then return 0, 1, false end
z = a[1][1] * a[2][2] - a[1][2] * a[2][1]
z = (a[1][1] + a[1][2] + a[2][1] + a[2][2]) * z * z / x
return z, math.igamma(.5, .5 * z, true), true
else -- generic table
local rs, cs, n, m, N, z = {}, {}, #a, #a[1], 0, 0
for i = 1, n do rs[i] = 0 end
for j = 1, m do cs[j] = 0 end
for i = 1, n do -- compute column sum and row sum
for j = 1, m do cs[j], rs[i] = cs[j] + a[i][j], rs[i] + a[i][j] end
end
for i = 1, n do N = N + rs[i] end
for i = 1, n do -- compute the chi^2 statistics
for j = 1, m do
local E = rs[i] * cs[j] / N;
z = z + (a[i][j] - E) * (a[i][j] - E) / E
end
end
return z, math.igamma(.5 * (n-1) * (m-1), .5 * z, true), true;
end
end
-- Description: Gauss-Jordan elimination (solving equations; computing inverse)
-- Note: on return, a[n][n] is the inverse; b[n][m] is the solution
-- Reference: Section 2.1, Numerical Recipes in C, 2nd edition
function matrix.solve(a, b)
assert(#a == #a[1]);
local n, m = #a, (b and #b[1]) or 0;
local xc, xr, ipiv = {}, {}, {};
local ic, ir;
for j = 1, n do ipiv[j] = 0 end
for i = 1, n do
local big = 0;
for j = 1, n do
local aj = a[j];
if ipiv[j] ~= 1 then
for k = 1, n do
if ipiv[k] == 0 then
if math.abs(aj[k]) >= big then
big = math.abs(aj[k]);
ir, ic = j, k;
end
elseif ipiv[k] > 1 then return -2 end -- singular matrix
end
end
end
ipiv[ic] = ipiv[ic] + 1;
if ir ~= ic then
for l = 1, n do a[ir][l], a[ic][l] = a[ic][l], a[ir][l] end
if b then
for l = 1, m do b[ir][l], b[ic][l] = b[ic][l], b[ir][l] end
end
end
xr[i], xc[i] = ir, ic;
if a[ic][ic] == 0 then return -3 end -- singular matrix
local pivinv = 1 / a[ic][ic];
a[ic][ic] = 1;
for l = 1, n do a[ic][l] = a[ic][l] * pivinv end
if b then
for l = 1, n do b[ic][l] = b[ic][l] * pivinv end
end
for ll = 1, n do
if ll ~= ic then
local tmp = a[ll][ic];
a[ll][ic] = 0;
local all, aic = a[ll], a[ic];
for l = 1, n do all[l] = all[l] - aic[l] * tmp end
if b then
local bll, bic = b[ll], b[ic];
for l = 1, m do bll[l] = bll[l] - bic[l] * tmp end
end
end
end
end
for l = n, 1, -1 do
if xr[l] ~= xc[l] then
for k = 1, n do a[k][xr[l]], a[k][xc[l]] = a[k][xc[l]], a[k][xr[l]] end
end
end
return 0;
end
| gpl-2.0 |
alobaidy98/ahmed.Dev | plugins/stats.lua | 4 | 4013 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(receiver, chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local receiver = get_receiver(msg)
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(receiver, chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin1(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin1(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[#!/]([Ss]tats)$",
"^[#!/]([Ss]tatslist)$",
"^[#!/]([Ss]tats) (group) (%d+)",
"^[#!/]([Ss]tats) (teleseed)",
"^[#!/]([Tt]eleseed)"
},
run = run
}
end | gpl-3.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/farm_decor.lua | 1 | 1355 |
local function makeassetlist(bankname, buildname)
return {
Asset("ANIM", "anim/"..buildname..".zip"),
Asset("ANIM", "anim/"..bankname..".zip"),
}
end
local function makefn(bankname, buildname, animname)
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst:AddTag("DECOR")
anim:SetBank(bankname)
anim:SetBuild(buildname)
anim:PlayAnimation(animname)
return inst
end
return fn
end
local function item(name, bankname, buildname, animname)
return Prefab( "forest/objects/farmdecor/"..name, makefn(bankname, buildname, animname), makeassetlist(bankname, buildname) )
end
return item("farmrock", "farm_decor", "farm_decor", "1"),
item("farmrocktall", "farm_decor", "farm_decor", "2"),
item("farmrockflat", "farm_decor", "farm_decor", "8"),
item("stick", "farm_decor", "farm_decor", "3"),
item("stickright", "farm_decor", "farm_decor", "6"),
item("stickleft", "farm_decor", "farm_decor", "7"),
item("signleft", "farm_decor", "farm_decor", "4"),
item("fencepost", "farm_decor", "farm_decor", "5"),
item("fencepostright", "farm_decor", "farm_decor", "9"),
item("signright", "farm_decor", "farm_decor", "10")
| gpl-2.0 |
Metastruct/gmod-csweapons | lua/weapons/weapon_fiveseven.lua | 1 | 3040 | AddCSLuaFile()
DEFINE_BASECLASS( "weapon_csbasegun" )
CSParseWeaponInfo( SWEP , [[WeaponData
{
"MaxPlayerSpeed" "250"
"WeaponType" "Pistol"
"FullAuto" 0
"WeaponPrice" "750"
"WeaponArmorRatio" "1.5"
"CrosshairMinDistance" "8"
"CrosshairDeltaDistance" "3"
"Team" "CT"
"BuiltRightHanded" "0"
"PlayerAnimationExtension" "pistol"
"MuzzleFlashScale" "1"
"CanEquipWithShield" "1"
// Weapon characteristics:
"Penetration" "1"
"Damage" "25"
"Range" "4096"
"RangeModifier" "0.885"
"Bullets" "1"
"CycleTime" "0.15"
// New accuracy model parameters
"Spread" 0.00400
"InaccuracyCrouch" 0.00600
"InaccuracyStand" 0.01000
"InaccuracyJump" 0.25635
"InaccuracyLand" 0.05127
"InaccuracyLadder" 0.01709
"InaccuracyFire" 0.05883
"InaccuracyMove" 0.01538
"RecoveryTimeCrouch" 0.18628
"RecoveryTimeStand" 0.22353
// Weapon data is loaded by both the Game and Client DLLs.
"printname" "#Cstrike_WPNHUD_FiveSeven"
"viewmodel" "models/weapons/v_pist_fiveseven.mdl"
"playermodel" "models/weapons/w_pist_fiveseven.mdl"
"shieldviewmodel" "models/weapons/v_shield_fiveseven_r.mdl"
"anim_prefix" "anim"
"bucket" "1"
"bucket_position" "1"
"clip_size" "20"
"primary_ammo" "BULLET_PLAYER_57MM"
"secondary_ammo" "None"
"weight" "5"
"item_flags" "0"
// Sounds for the weapon. There is a max of 16 sounds per category (i.e. max 16 "single_shot" sounds)
SoundData
{
//"reload" "Default.Reload"
//"empty" "Default.ClipEmpty_Rifle"
"single_shot" "Weapon_FiveSeven.Single"
}
// Weapon Sprite data is loaded by the Client DLL.
TextureData
{
"weapon"
{
"font" "CSweaponsSmall"
"character" "U"
}
"weapon_s"
{
"font" "CSweapons"
"character" "U"
}
"ammo"
{
"font" "CSTypeDeath"
"character" "S"
}
"crosshair"
{
"file" "sprites/crosshairs"
"x" "0"
"y" "48"
"width" "24"
"height" "24"
}
"autoaim"
{
"file" "sprites/crosshairs"
"x" "0"
"y" "48"
"width" "24"
"height" "24"
}
}
ModelBounds
{
Viewmodel
{
Mins "-8 -4 -16"
Maxs "18 9 -3"
}
World
{
Mins "-1 -3 -2"
Maxs "11 4 5"
}
}
}]] )
SWEP.Spawnable = true
SWEP.Slot = 1
SWEP.SlotPos = 0
function SWEP:Initialize()
BaseClass.Initialize( self )
self:SetHoldType( "pistol" )
self:SetWeaponID( CS_WEAPON_FIVESEVEN )
end
function SWEP:PrimaryAttack()
if self:GetNextPrimaryAttack() > CurTime() then return end
self:GunFire( self:BuildSpread() )
end
function SWEP:GunFire( spread )
if not self:BaseGunFire( spread, self:GetWeaponInfo().CycleTime, true ) then
return
end
if self:GetOwner():GetAbsVelocity():Length2D() > 5 then
self:KickBack( 0.45, 0.3, 0.2, 0.0275, 4, 2.25, 7 )
elseif not self:GetOwner():OnGround() then
self:KickBack( 0.9, 0.45, 0.35, 0.04, 5.25, 3.5, 4 )
elseif self:GetOwner():Crouching() then
self:KickBack( 0.275, 0.2, 0.125, 0.02, 3, 1, 9 )
else
self:KickBack( 0.3, 0.225, 0.125, 0.02, 3.25, 1.25, 8 )
end
end
| unlicense |
Mysticla/Electrostasis | lib/bump.lua | 4 | 21395 | local bump = {
_VERSION = 'bump v3.1.3',
_URL = 'https://github.com/kikito/bump.lua',
_DESCRIPTION = 'A collision detection library for Lua',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2014 Enrique García Cota
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.
]]
}
------------------------------------------
-- Auxiliary functions
------------------------------------------
local DELTA = 1e-10 -- floating-point margin of error
local abs, floor, ceil, min, max = math.abs, math.floor, math.ceil, math.min, math.max
local function sign(x)
if x > 0 then return 1 end
if x == 0 then return 0 end
return -1
end
local function nearest(x, a, b)
if abs(a - x) < abs(b - x) then return a else return b end
end
local function assertType(desiredType, value, name)
if type(value) ~= desiredType then
error(name .. ' must be a ' .. desiredType .. ', but was ' .. tostring(value) .. '(a ' .. type(value) .. ')')
end
end
local function assertIsPositiveNumber(value, name)
if type(value) ~= 'number' or value <= 0 then
error(name .. ' must be a positive integer, but was ' .. tostring(value) .. '(' .. type(value) .. ')')
end
end
local function assertIsRect(x,y,w,h)
assertType('number', x, 'x')
assertType('number', y, 'y')
assertIsPositiveNumber(w, 'w')
assertIsPositiveNumber(h, 'h')
end
local defaultFilter = function()
return 'slide'
end
------------------------------------------
-- Rectangle functions
------------------------------------------
local function rect_getNearestCorner(x,y,w,h, px, py)
return nearest(px, x, x+w), nearest(py, y, y+h)
end
-- This is a generalized implementation of the liang-barsky algorithm, which also returns
-- the normals of the sides where the segment intersects.
-- Returns nil if the segment never touches the rect
-- Notice that normals are only guaranteed to be accurate when initially ti1, ti2 == -math.huge, math.huge
local function rect_getSegmentIntersectionIndices(x,y,w,h, x1,y1,x2,y2, ti1,ti2)
ti1, ti2 = ti1 or 0, ti2 or 1
local dx, dy = x2-x1, y2-y1
local nx, ny
local nx1, ny1, nx2, ny2 = 0,0,0,0
local p, q, r
for side = 1,4 do
if side == 1 then nx,ny,p,q = -1, 0, -dx, x1 - x -- left
elseif side == 2 then nx,ny,p,q = 1, 0, dx, x + w - x1 -- right
elseif side == 3 then nx,ny,p,q = 0, -1, -dy, y1 - y -- top
else nx,ny,p,q = 0, 1, dy, y + h - y1 -- bottom
end
if p == 0 then
if q <= 0 then return nil end
else
r = q / p
if p < 0 then
if r > ti2 then return nil
elseif r > ti1 then ti1,nx1,ny1 = r,nx,ny
end
else -- p > 0
if r < ti1 then return nil
elseif r < ti2 then ti2,nx2,ny2 = r,nx,ny
end
end
end
end
return ti1,ti2, nx1,ny1, nx2,ny2
end
-- Calculates the minkowsky difference between 2 rects, which is another rect
local function rect_getDiff(x1,y1,w1,h1, x2,y2,w2,h2)
return x2 - x1 - w1,
y2 - y1 - h1,
w1 + w2,
h1 + h2
end
local function rect_containsPoint(x,y,w,h, px,py)
return px - x > DELTA and py - y > DELTA and
x + w - px > DELTA and y + h - py > DELTA
end
local function rect_isIntersecting(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and x2 < x1+w1 and
y1 < y2+h2 and y2 < y1+h1
end
local function rect_getSquareDistance(x1,y1,w1,h1, x2,y2,w2,h2)
local dx = x1 - x2 + (w1 - w2)/2
local dy = y1 - y2 + (h1 - h2)/2
return dx*dx + dy*dy
end
local function rect_detectCollision(x1,y1,w1,h1, x2,y2,w2,h2, goalX, goalY)
goalX = goalX or x1
goalY = goalY or y1
local dx, dy = goalX - x1, goalY - y1
local x,y,w,h = rect_getDiff(x1,y1,w1,h1, x2,y2,w2,h2)
local overlaps, ti, nx, ny
if rect_containsPoint(x,y,w,h, 0,0) then -- item was intersecting other
local px, py = rect_getNearestCorner(x,y,w,h, 0, 0)
local wi, hi = min(w1, abs(px)), min(h1, abs(py)) -- area of intersection
ti = -wi * hi -- ti is the negative area of intersection
overlaps = true
else
local ti1,ti2,nx1,ny1 = rect_getSegmentIntersectionIndices(x,y,w,h, 0,0,dx,dy, -math.huge, math.huge)
-- item tunnels into other
if ti1 and ti1 < 1 and (0 < ti1 + DELTA or 0 == ti1 and ti2 > 0) then
ti, nx, ny = ti1, nx1, ny1
overlaps = false
end
end
if not ti then return end
local tx, ty
if overlaps then
if dx == 0 and dy == 0 then
-- intersecting and not moving - use minimum displacement vector
local px, py = rect_getNearestCorner(x,y,w,h, 0,0)
if abs(px) < abs(py) then py = 0 else px = 0 end
nx, ny = sign(px), sign(py)
tx, ty = x1 + px, y1 + py
else
-- intersecting and moving - move in the opposite direction
local ti1
ti1,_,nx,ny = rect_getSegmentIntersectionIndices(x,y,w,h, 0,0,dx,dy, -math.huge, 1)
if not ti1 then return end
tx, ty = x1 + dx * ti1, y1 + dy * ti1
end
else -- tunnel
tx, ty = x1 + dx * ti, y1 + dy * ti
end
return {
overlaps = overlaps,
ti = ti,
move = {x = dx, y = dy},
normal = {x = nx, y = ny},
touch = {x = tx, y = ty},
itemRect = {x = x1, y = y1, w = w1, h = h1},
otherRect = {x = x2, y = y2, w = w2, h = h2}
}
end
------------------------------------------
-- Grid functions
------------------------------------------
local function grid_toWorld(cellSize, cx, cy)
return (cx - 1)*cellSize, (cy-1)*cellSize
end
local function grid_toCell(cellSize, x, y)
return floor(x / cellSize) + 1, floor(y / cellSize) + 1
end
-- grid_traverse* functions are based on "A Fast Voxel Traversal Algorithm for Ray Tracing",
-- by John Amanides and Andrew Woo - http://www.cse.yorku.ca/~amana/research/grid.pdf
-- It has been modified to include both cells when the ray "touches a grid corner",
-- and with a different exit condition
local function grid_traverse_initStep(cellSize, ct, t1, t2)
local v = t2 - t1
if v > 0 then
return 1, cellSize / v, ((ct + v) * cellSize - t1) / v
elseif v < 0 then
return -1, -cellSize / v, ((ct + v - 1) * cellSize - t1) / v
else
return 0, math.huge, math.huge
end
end
local function grid_traverse(cellSize, x1,y1,x2,y2, f)
local cx1,cy1 = grid_toCell(cellSize, x1,y1)
local cx2,cy2 = grid_toCell(cellSize, x2,y2)
local stepX, dx, tx = grid_traverse_initStep(cellSize, cx1, x1, x2)
local stepY, dy, ty = grid_traverse_initStep(cellSize, cy1, y1, y2)
local cx,cy = cx1,cy1
f(cx, cy)
-- The default implementation had an infinite loop problem when
-- approaching the last cell in some occassions. We finish iterating
-- when we are *next* to the last cell
while abs(cx - cx2) + abs(cy - cy2) > 1 do
if tx < ty then
tx, cx = tx + dx, cx + stepX
f(cx, cy)
else
-- Addition: include both cells when going through corners
if tx == ty then f(cx + stepX, cy) end
ty, cy = ty + dy, cy + stepY
f(cx, cy)
end
end
-- If we have not arrived to the last cell, use it
if cx ~= cx2 or cy ~= cy2 then f(cx2, cy2) end
end
local function grid_toCellRect(cellSize, x,y,w,h)
local cx,cy = grid_toCell(cellSize, x, y)
local cr,cb = ceil((x+w) / cellSize), ceil((y+h) / cellSize)
return cx, cy, cr - cx + 1, cb - cy + 1
end
------------------------------------------
-- Responses
------------------------------------------
local touch = function(world, col, x,y,w,h, goalX, goalY, filter)
local touch = col.touch
return touch.x, touch.y, {}, 0
end
local cross = function(world, col, x,y,w,h, goalX, goalY, filter)
local touch = col.touch
local cols, len = world:project(col.item, x,y,w,h, goalX, goalY, filter)
return goalX, goalY, cols, len
end
local slide = function(world, col, x,y,w,h, goalX, goalY, filter)
goalX = goalX or x
goalY = goalY or y
local touch, move = col.touch, col.move
local sx, sy = touch.x, touch.y
if move.x ~= 0 or move.y ~= 0 then
if col.normal.x == 0 then
sx = goalX
else
sy = goalY
end
end
col.slide = {x = sx, y = sy}
x,y = touch.x, touch.y
goalX, goalY = sx, sy
local cols, len = world:project(col.item, x,y,w,h, goalX, goalY, filter)
return goalX, goalY, cols, len
end
local bounce = function(world, col, x,y,w,h, goalX, goalY, filter)
goalX = goalX or x
goalY = goalY or y
local touch, move = col.touch, col.move
local tx, ty = touch.x, touch.y
local bx, by, bnx, bny = tx, ty, 0,0
if move.x ~= 0 or move.y ~= 0 then
bnx, bny = goalX - tx, goalY - ty
if col.normal.x == 0 then bny = -bny else bnx = -bnx end
bx, by = tx + bnx, ty + bny
end
col.bounce = {x = bx, y = by}
x,y = touch.x, touch.y
goalX, goalY = bx, by
local cols, len = world:project(col.item, x,y,w,h, goalX, goalY, filter)
return goalX, goalY, cols, len
end
------------------------------------------
-- World
------------------------------------------
local World = {}
local World_mt = {__index = World}
-- Private functions and methods
local function sortByWeight(a,b) return a.weight < b.weight end
local function sortByTiAndDistance(a,b)
if a.ti == b.ti then
local ir, ar, br = a.itemRect, a.otherRect, b.otherRect
local ad = rect_getSquareDistance(ir.x,ir.y,ir.w,ir.h, ar.x,ar.y,ar.w,ar.h)
local bd = rect_getSquareDistance(ir.x,ir.y,ir.w,ir.h, br.x,br.y,br.w,br.h)
return ad < bd
end
return a.ti < b.ti
end
local function addItemToCell(self, item, cx, cy)
self.rows[cy] = self.rows[cy] or setmetatable({}, {__mode = 'v'})
local row = self.rows[cy]
row[cx] = row[cx] or {itemCount = 0, x = cx, y = cy, items = setmetatable({}, {__mode = 'k'})}
local cell = row[cx]
self.nonEmptyCells[cell] = true
if not cell.items[item] then
cell.items[item] = true
cell.itemCount = cell.itemCount + 1
end
end
local function removeItemFromCell(self, item, cx, cy)
local row = self.rows[cy]
if not row or not row[cx] or not row[cx].items[item] then return false end
local cell = row[cx]
cell.items[item] = nil
cell.itemCount = cell.itemCount - 1
if cell.itemCount == 0 then
self.nonEmptyCells[cell] = nil
end
return true
end
local function getDictItemsInCellRect(self, cl,ct,cw,ch)
local items_dict = {}
for cy=ct,ct+ch-1 do
local row = self.rows[cy]
if row then
for cx=cl,cl+cw-1 do
local cell = row[cx]
if cell and cell.itemCount > 0 then -- no cell.itemCount > 1 because tunneling
for item,_ in pairs(cell.items) do
items_dict[item] = true
end
end
end
end
end
return items_dict
end
local function getCellsTouchedBySegment(self, x1,y1,x2,y2)
local cells, cellsLen, visited = {}, 0, {}
grid_traverse(self.cellSize, x1,y1,x2,y2, function(cx, cy)
local row = self.rows[cy]
if not row then return end
local cell = row[cx]
if not cell or visited[cell] then return end
visited[cell] = true
cellsLen = cellsLen + 1
cells[cellsLen] = cell
end)
return cells, cellsLen
end
local function getInfoAboutItemsTouchedBySegment(self, x1,y1, x2,y2, filter)
local cells, len = getCellsTouchedBySegment(self, x1,y1,x2,y2)
local cell, rect, l,t,w,h, ti1,ti2, tii0,tii1
local visited, itemInfo, itemInfoLen = {},{},0
for i=1,len do
cell = cells[i]
for item in pairs(cell.items) do
if not visited[item] then
visited[item] = true
if (not filter or filter(item)) then
rect = self.rects[item]
l,t,w,h = rect.x,rect.y,rect.w,rect.h
ti1,ti2 = rect_getSegmentIntersectionIndices(l,t,w,h, x1,y1, x2,y2, 0, 1)
if ti1 and ((0 < ti1 and ti1 < 1) or (0 < ti2 and ti2 < 1)) then
-- the sorting is according to the t of an infinite line, not the segment
tii0,tii1 = rect_getSegmentIntersectionIndices(l,t,w,h, x1,y1, x2,y2, -math.huge, math.huge)
itemInfoLen = itemInfoLen + 1
itemInfo[itemInfoLen] = {item = item, ti1 = ti1, ti2 = ti2, weight = min(tii0,tii1)}
end
end
end
end
end
table.sort(itemInfo, sortByWeight)
return itemInfo, itemInfoLen
end
local function getResponseByName(self, name)
local response = self.responses[name]
if not response then
error(('Unknown collision type: %s (%s)'):format(name, type(name)))
end
return response
end
-- Misc Public Methods
function World:addResponse(name, response)
self.responses[name] = response
end
function World:project(item, x,y,w,h, goalX, goalY, filter)
assertIsRect(x,y,w,h)
goalX = goalX or x
goalY = goalY or y
filter = filter or defaultFilter
local collisions, len = {}, 0
local visited = {}
if item ~= nil then visited[item] = true end
-- This could probably be done with less cells using a polygon raster over the cells instead of a
-- bounding rect of the whole movement. Conditional to building a queryPolygon method
local tl, tt = min(goalX, x), min(goalY, y)
local tr, tb = max(goalX + w, x+w), max(goalY + h, y+h)
local tw, th = tr-tl, tb-tt
local cl,ct,cw,ch = grid_toCellRect(self.cellSize, tl,tt,tw,th)
local dictItemsInCellRect = getDictItemsInCellRect(self, cl,ct,cw,ch)
for other,_ in pairs(dictItemsInCellRect) do
if not visited[other] then
visited[other] = true
local responseName = filter(item, other)
if responseName then
local ox,oy,ow,oh = self:getRect(other)
local col = rect_detectCollision(x,y,w,h, ox,oy,ow,oh, goalX, goalY)
if col then
col.other = other
col.item = item
col.type = responseName
len = len + 1
collisions[len] = col
end
end
end
end
table.sort(collisions, sortByTiAndDistance)
return collisions, len
end
function World:countCells()
local count = 0
for _,row in pairs(self.rows) do
for _,_ in pairs(row) do
count = count + 1
end
end
return count
end
function World:hasItem(item)
return not not self.rects[item]
end
function World:getItems()
local items, len = {}, 0
for item,_ in pairs(self.rects) do
len = len + 1
items[len] = item
end
return items, len
end
function World:countItems()
local len = 0
for _ in pairs(self.rects) do len = len + 1 end
return len
end
function World:getRect(item)
local rect = self.rects[item]
if not rect then
error('Item ' .. tostring(item) .. ' must be added to the world before getting its rect. Use world:add(item, x,y,w,h) to add it first.')
end
return rect.x, rect.y, rect.w, rect.h
end
function World:toWorld(cx, cy)
return grid_toWorld(self.cellSize, cx, cy)
end
function World:toCell(x,y)
return grid_toCell(self.cellSize, x, y)
end
--- Query methods
function World:queryRect(x,y,w,h, filter)
local cl,ct,cw,ch = grid_toCellRect(self.cellSize, x,y,w,h)
local dictItemsInCellRect = getDictItemsInCellRect(self, cl,ct,cw,ch)
local items, len = {}, 0
local rect
for item,_ in pairs(dictItemsInCellRect) do
rect = self.rects[item]
if (not filter or filter(item))
and rect_isIntersecting(x,y,w,h, rect.x, rect.y, rect.w, rect.h)
then
len = len + 1
items[len] = item
end
end
return items, len
end
function World:queryPoint(x,y, filter)
local cx,cy = self:toCell(x,y)
local dictItemsInCellRect = getDictItemsInCellRect(self, cx,cy,1,1)
local items, len = {}, 0
local rect
for item,_ in pairs(dictItemsInCellRect) do
rect = self.rects[item]
if (not filter or filter(item))
and rect_containsPoint(rect.x, rect.y, rect.w, rect.h, x, y)
then
len = len + 1
items[len] = item
end
end
return items, len
end
function World:querySegment(x1, y1, x2, y2, filter)
local itemInfo, len = getInfoAboutItemsTouchedBySegment(self, x1, y1, x2, y2, filter)
local items = {}
for i=1, len do
items[i] = itemInfo[i].item
end
return items, len
end
function World:querySegmentWithCoords(x1, y1, x2, y2, filter)
local itemInfo, len = getInfoAboutItemsTouchedBySegment(self, x1, y1, x2, y2, filter)
local dx, dy = x2-x1, y2-y1
local info, ti1, ti2
for i=1, len do
info = itemInfo[i]
ti1 = info.ti1
ti2 = info.ti2
info.weight = nil
info.x1 = x1 + dx * ti1
info.y1 = y1 + dy * ti1
info.x2 = x1 + dx * ti2
info.y2 = y1 + dy * ti2
end
return itemInfo, len
end
--- Main methods
function World:add(item, x,y,w,h)
local rect = self.rects[item]
if rect then
error('Item ' .. tostring(item) .. ' added to the world twice.')
end
assertIsRect(x,y,w,h)
self.rects[item] = {x=x,y=y,w=w,h=h}
local cl,ct,cw,ch = grid_toCellRect(self.cellSize, x,y,w,h)
for cy = ct, ct+ch-1 do
for cx = cl, cl+cw-1 do
addItemToCell(self, item, cx, cy)
end
end
return item
end
function World:remove(item)
local x,y,w,h = self:getRect(item)
self.rects[item] = nil
local cl,ct,cw,ch = grid_toCellRect(self.cellSize, x,y,w,h)
for cy = ct, ct+ch-1 do
for cx = cl, cl+cw-1 do
removeItemFromCell(self, item, cx, cy)
end
end
end
function World:update(item, x2,y2,w2,h2)
local x1,y1,w1,h1 = self:getRect(item)
w2,h2 = w2 or w1, h2 or h1
assertIsRect(x2,y2,w2,h2)
if x1 ~= x2 or y1 ~= y2 or w1 ~= w2 or h1 ~= h2 then
local cellSize = self.cellSize
local cl1,ct1,cw1,ch1 = grid_toCellRect(cellSize, x1,y1,w1,h1)
local cl2,ct2,cw2,ch2 = grid_toCellRect(cellSize, x2,y2,w2,h2)
if cl1 ~= cl2 or ct1 ~= ct2 or cw1 ~= cw2 or ch1 ~= ch2 then
local cr1, cb1 = cl1+cw1-1, ct1+ch1-1
local cr2, cb2 = cl2+cw2-1, ct2+ch2-1
local cyOut
for cy = ct1, cb1 do
cyOut = cy < ct2 or cy > cb2
for cx = cl1, cr1 do
if cyOut or cx < cl2 or cx > cr2 then
removeItemFromCell(self, item, cx, cy)
end
end
end
for cy = ct2, cb2 do
cyOut = cy < ct1 or cy > cb1
for cx = cl2, cr2 do
if cyOut or cx < cl1 or cx > cr1 then
addItemToCell(self, item, cx, cy)
end
end
end
end
local rect = self.rects[item]
rect.x, rect.y, rect.w, rect.h = x2,y2,w2,h2
end
end
function World:move(item, goalX, goalY, filter)
local actualX, actualY, cols, len = self:check(item, goalX, goalY, filter)
self:update(item, actualX, actualY)
return actualX, actualY, cols, len
end
function World:check(item, goalX, goalY, filter)
filter = filter or defaultFilter
local visited = {[item] = true}
local visitedFilter = function(item, other)
if visited[other] then return false end
return filter(item, other)
end
local cols, len = {}, 0
local x,y,w,h = self:getRect(item)
local projected_cols, projected_len = self:project(item, x,y,w,h, goalX,goalY, visitedFilter)
while projected_len > 0 do
local col = projected_cols[1]
len = len + 1
cols[len] = col
visited[col.other] = true
local response = getResponseByName(self, col.type)
goalX, goalY, projected_cols, projected_len = response(
self,
col,
x, y, w, h,
goalX, goalY,
visitedFilter
)
end
return goalX, goalY, cols, len
end
-- Public library functions
bump.newWorld = function(cellSize)
cellSize = cellSize or 64
assertIsPositiveNumber(cellSize, 'cellSize')
local world = setmetatable({
cellSize = cellSize,
rects = {},
rows = {},
nonEmptyCells = {},
responses = {}
}, World_mt)
world:addResponse('touch', touch)
world:addResponse('cross', cross)
world:addResponse('slide', slide)
world:addResponse('bounce', bounce)
return world
end
bump.rect = {
getNearestCorner = rect_getNearestCorner,
getSegmentIntersectionIndices = rect_getSegmentIntersectionIndices,
getDiff = rect_getDiff,
containsPoint = rect_containsPoint,
isIntersecting = rect_isIntersecting,
getSquareDistance = rect_getSquareDistance,
detectCollision = rect_detectCollision
}
bump.responses = {
touch = touch,
cross = cross,
slide = slide,
bounce = bounce
}
return bump
| mit |
v3n/altertum | ext/luajit/dynasm/dasm_ppc.lua | 39 | 57489 | ------------------------------------------------------------------------------
-- DynASM PPC/PPC64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
--
-- Support for various extensions contributed by Caio Souza Oliveira.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "ppc",
description = "DynASM PPC module",
version = "1.3.0",
vernum = 10300,
release = "2015-01-14",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable = assert, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch = _s.match, _s.gmatch
local concat, sort = table.concat, table.sort
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local tohex = bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMMSH"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0xffffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = { sp = "r1" } -- Ext. register name -> int. name.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
if s == "r1" then return "sp" end
return s
end
local map_cond = {
lt = 0, gt = 1, eq = 2, so = 3,
ge = 4, le = 5, ne = 6, ns = 7,
}
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
-- Template strings for PPC instructions.
map_op = {
tdi_3 = "08000000ARI",
twi_3 = "0c000000ARI",
mulli_3 = "1c000000RRI",
subfic_3 = "20000000RRI",
cmplwi_3 = "28000000XRU",
cmplwi_2 = "28000000-RU",
cmpldi_3 = "28200000XRU",
cmpldi_2 = "28200000-RU",
cmpwi_3 = "2c000000XRI",
cmpwi_2 = "2c000000-RI",
cmpdi_3 = "2c200000XRI",
cmpdi_2 = "2c200000-RI",
addic_3 = "30000000RRI",
["addic._3"] = "34000000RRI",
addi_3 = "38000000RR0I",
li_2 = "38000000RI",
la_2 = "38000000RD",
addis_3 = "3c000000RR0I",
lis_2 = "3c000000RI",
lus_2 = "3c000000RU",
bc_3 = "40000000AAK",
bcl_3 = "40000001AAK",
bdnz_1 = "42000000K",
bdz_1 = "42400000K",
sc_0 = "44000000",
b_1 = "48000000J",
bl_1 = "48000001J",
rlwimi_5 = "50000000RR~AAA.",
rlwinm_5 = "54000000RR~AAA.",
rlwnm_5 = "5c000000RR~RAA.",
ori_3 = "60000000RR~U",
nop_0 = "60000000",
oris_3 = "64000000RR~U",
xori_3 = "68000000RR~U",
xoris_3 = "6c000000RR~U",
["andi._3"] = "70000000RR~U",
["andis._3"] = "74000000RR~U",
lwz_2 = "80000000RD",
lwzu_2 = "84000000RD",
lbz_2 = "88000000RD",
lbzu_2 = "8c000000RD",
stw_2 = "90000000RD",
stwu_2 = "94000000RD",
stb_2 = "98000000RD",
stbu_2 = "9c000000RD",
lhz_2 = "a0000000RD",
lhzu_2 = "a4000000RD",
lha_2 = "a8000000RD",
lhau_2 = "ac000000RD",
sth_2 = "b0000000RD",
sthu_2 = "b4000000RD",
lmw_2 = "b8000000RD",
stmw_2 = "bc000000RD",
lfs_2 = "c0000000FD",
lfsu_2 = "c4000000FD",
lfd_2 = "c8000000FD",
lfdu_2 = "cc000000FD",
stfs_2 = "d0000000FD",
stfsu_2 = "d4000000FD",
stfd_2 = "d8000000FD",
stfdu_2 = "dc000000FD",
ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4.
ldu_2 = "e8000001RD",
lwa_2 = "e8000002RD",
std_2 = "f8000000RD",
stdu_2 = "f8000001RD",
subi_3 = op_alias("addi_3", function(p) p[3] = "-("..p[3]..")" end),
subis_3 = op_alias("addis_3", function(p) p[3] = "-("..p[3]..")" end),
subic_3 = op_alias("addic_3", function(p) p[3] = "-("..p[3]..")" end),
["subic._3"] = op_alias("addic._3", function(p) p[3] = "-("..p[3]..")" end),
rotlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
rotrwi_3 = op_alias("rlwinm_5", function(p)
p[3] = "32-("..p[3]..")"; p[4] = "0"; p[5] = "31"
end),
rotlw_3 = op_alias("rlwnm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
slwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[4] = "0"
end),
srwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "32-("..p[3]..")"; p[5] = "31"
end),
clrlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "0"; p[5] = "31"
end),
clrrwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[3] = "0"; p[4] = "0"
end),
-- Primary opcode 4:
mulhhwu_3 = "10000010RRR.",
machhwu_3 = "10000018RRR.",
mulhhw_3 = "10000050RRR.",
nmachhw_3 = "1000005cRRR.",
machhwsu_3 = "10000098RRR.",
machhws_3 = "100000d8RRR.",
nmachhws_3 = "100000dcRRR.",
mulchwu_3 = "10000110RRR.",
macchwu_3 = "10000118RRR.",
mulchw_3 = "10000150RRR.",
macchw_3 = "10000158RRR.",
nmacchw_3 = "1000015cRRR.",
macchwsu_3 = "10000198RRR.",
macchws_3 = "100001d8RRR.",
nmacchws_3 = "100001dcRRR.",
mullhw_3 = "10000350RRR.",
maclhw_3 = "10000358RRR.",
nmaclhw_3 = "1000035cRRR.",
maclhwsu_3 = "10000398RRR.",
maclhws_3 = "100003d8RRR.",
nmaclhws_3 = "100003dcRRR.",
machhwuo_3 = "10000418RRR.",
nmachhwo_3 = "1000045cRRR.",
machhwsuo_3 = "10000498RRR.",
machhwso_3 = "100004d8RRR.",
nmachhwso_3 = "100004dcRRR.",
macchwuo_3 = "10000518RRR.",
macchwo_3 = "10000558RRR.",
nmacchwo_3 = "1000055cRRR.",
macchwsuo_3 = "10000598RRR.",
macchwso_3 = "100005d8RRR.",
nmacchwso_3 = "100005dcRRR.",
maclhwo_3 = "10000758RRR.",
nmaclhwo_3 = "1000075cRRR.",
maclhwsuo_3 = "10000798RRR.",
maclhwso_3 = "100007d8RRR.",
nmaclhwso_3 = "100007dcRRR.",
vaddubm_3 = "10000000VVV",
vmaxub_3 = "10000002VVV",
vrlb_3 = "10000004VVV",
vcmpequb_3 = "10000006VVV",
vmuloub_3 = "10000008VVV",
vaddfp_3 = "1000000aVVV",
vmrghb_3 = "1000000cVVV",
vpkuhum_3 = "1000000eVVV",
vmhaddshs_4 = "10000020VVVV",
vmhraddshs_4 = "10000021VVVV",
vmladduhm_4 = "10000022VVVV",
vmsumubm_4 = "10000024VVVV",
vmsummbm_4 = "10000025VVVV",
vmsumuhm_4 = "10000026VVVV",
vmsumuhs_4 = "10000027VVVV",
vmsumshm_4 = "10000028VVVV",
vmsumshs_4 = "10000029VVVV",
vsel_4 = "1000002aVVVV",
vperm_4 = "1000002bVVVV",
vsldoi_4 = "1000002cVVVP",
vpermxor_4 = "1000002dVVVV",
vmaddfp_4 = "1000002eVVVV~",
vnmsubfp_4 = "1000002fVVVV~",
vaddeuqm_4 = "1000003cVVVV",
vaddecuq_4 = "1000003dVVVV",
vsubeuqm_4 = "1000003eVVVV",
vsubecuq_4 = "1000003fVVVV",
vadduhm_3 = "10000040VVV",
vmaxuh_3 = "10000042VVV",
vrlh_3 = "10000044VVV",
vcmpequh_3 = "10000046VVV",
vmulouh_3 = "10000048VVV",
vsubfp_3 = "1000004aVVV",
vmrghh_3 = "1000004cVVV",
vpkuwum_3 = "1000004eVVV",
vadduwm_3 = "10000080VVV",
vmaxuw_3 = "10000082VVV",
vrlw_3 = "10000084VVV",
vcmpequw_3 = "10000086VVV",
vmulouw_3 = "10000088VVV",
vmuluwm_3 = "10000089VVV",
vmrghw_3 = "1000008cVVV",
vpkuhus_3 = "1000008eVVV",
vaddudm_3 = "100000c0VVV",
vmaxud_3 = "100000c2VVV",
vrld_3 = "100000c4VVV",
vcmpeqfp_3 = "100000c6VVV",
vcmpequd_3 = "100000c7VVV",
vpkuwus_3 = "100000ceVVV",
vadduqm_3 = "10000100VVV",
vmaxsb_3 = "10000102VVV",
vslb_3 = "10000104VVV",
vmulosb_3 = "10000108VVV",
vrefp_2 = "1000010aV-V",
vmrglb_3 = "1000010cVVV",
vpkshus_3 = "1000010eVVV",
vaddcuq_3 = "10000140VVV",
vmaxsh_3 = "10000142VVV",
vslh_3 = "10000144VVV",
vmulosh_3 = "10000148VVV",
vrsqrtefp_2 = "1000014aV-V",
vmrglh_3 = "1000014cVVV",
vpkswus_3 = "1000014eVVV",
vaddcuw_3 = "10000180VVV",
vmaxsw_3 = "10000182VVV",
vslw_3 = "10000184VVV",
vmulosw_3 = "10000188VVV",
vexptefp_2 = "1000018aV-V",
vmrglw_3 = "1000018cVVV",
vpkshss_3 = "1000018eVVV",
vmaxsd_3 = "100001c2VVV",
vsl_3 = "100001c4VVV",
vcmpgefp_3 = "100001c6VVV",
vlogefp_2 = "100001caV-V",
vpkswss_3 = "100001ceVVV",
vadduhs_3 = "10000240VVV",
vminuh_3 = "10000242VVV",
vsrh_3 = "10000244VVV",
vcmpgtuh_3 = "10000246VVV",
vmuleuh_3 = "10000248VVV",
vrfiz_2 = "1000024aV-V",
vsplth_3 = "1000024cVV3",
vupkhsh_2 = "1000024eV-V",
vminuw_3 = "10000282VVV",
vminud_3 = "100002c2VVV",
vcmpgtud_3 = "100002c7VVV",
vrfim_2 = "100002caV-V",
vcmpgtsb_3 = "10000306VVV",
vcfux_3 = "1000030aVVA~",
vaddshs_3 = "10000340VVV",
vminsh_3 = "10000342VVV",
vsrah_3 = "10000344VVV",
vcmpgtsh_3 = "10000346VVV",
vmulesh_3 = "10000348VVV",
vcfsx_3 = "1000034aVVA~",
vspltish_2 = "1000034cVS",
vupkhpx_2 = "1000034eV-V",
vaddsws_3 = "10000380VVV",
vminsw_3 = "10000382VVV",
vsraw_3 = "10000384VVV",
vcmpgtsw_3 = "10000386VVV",
vmulesw_3 = "10000388VVV",
vctuxs_3 = "1000038aVVA~",
vspltisw_2 = "1000038cVS",
vminsd_3 = "100003c2VVV",
vsrad_3 = "100003c4VVV",
vcmpbfp_3 = "100003c6VVV",
vcmpgtsd_3 = "100003c7VVV",
vctsxs_3 = "100003caVVA~",
vupklpx_2 = "100003ceV-V",
vsububm_3 = "10000400VVV",
["bcdadd._4"] = "10000401VVVy.",
vavgub_3 = "10000402VVV",
vand_3 = "10000404VVV",
["vcmpequb._3"] = "10000406VVV",
vmaxfp_3 = "1000040aVVV",
vsubuhm_3 = "10000440VVV",
["bcdsub._4"] = "10000441VVVy.",
vavguh_3 = "10000442VVV",
vandc_3 = "10000444VVV",
["vcmpequh._3"] = "10000446VVV",
vminfp_3 = "1000044aVVV",
vpkudum_3 = "1000044eVVV",
vsubuwm_3 = "10000480VVV",
vavguw_3 = "10000482VVV",
vor_3 = "10000484VVV",
["vcmpequw._3"] = "10000486VVV",
vpmsumw_3 = "10000488VVV",
["vcmpeqfp._3"] = "100004c6VVV",
["vcmpequd._3"] = "100004c7VVV",
vpkudus_3 = "100004ceVVV",
vavgsb_3 = "10000502VVV",
vavgsh_3 = "10000542VVV",
vorc_3 = "10000544VVV",
vbpermq_3 = "1000054cVVV",
vpksdus_3 = "1000054eVVV",
vavgsw_3 = "10000582VVV",
vsld_3 = "100005c4VVV",
["vcmpgefp._3"] = "100005c6VVV",
vpksdss_3 = "100005ceVVV",
vsububs_3 = "10000600VVV",
mfvscr_1 = "10000604V--",
vsum4ubs_3 = "10000608VVV",
vsubuhs_3 = "10000640VVV",
mtvscr_1 = "10000644--V",
["vcmpgtuh._3"] = "10000646VVV",
vsum4shs_3 = "10000648VVV",
vupkhsw_2 = "1000064eV-V",
vsubuws_3 = "10000680VVV",
vshasigmaw_4 = "10000682VVYp",
veqv_3 = "10000684VVV",
vsum2sws_3 = "10000688VVV",
vmrgow_3 = "1000068cVVV",
vshasigmad_4 = "100006c2VVYp",
vsrd_3 = "100006c4VVV",
["vcmpgtud._3"] = "100006c7VVV",
vupklsw_2 = "100006ceV-V",
vupkslw_2 = "100006ceV-V",
vsubsbs_3 = "10000700VVV",
vclzb_2 = "10000702V-V",
vpopcntb_2 = "10000703V-V",
["vcmpgtsb._3"] = "10000706VVV",
vsum4sbs_3 = "10000708VVV",
vsubshs_3 = "10000740VVV",
vclzh_2 = "10000742V-V",
vpopcnth_2 = "10000743V-V",
["vcmpgtsh._3"] = "10000746VVV",
vsubsws_3 = "10000780VVV",
vclzw_2 = "10000782V-V",
vpopcntw_2 = "10000783V-V",
["vcmpgtsw._3"] = "10000786VVV",
vsumsws_3 = "10000788VVV",
vmrgew_3 = "1000078cVVV",
vclzd_2 = "100007c2V-V",
vpopcntd_2 = "100007c3V-V",
["vcmpbfp._3"] = "100007c6VVV",
["vcmpgtsd._3"] = "100007c7VVV",
-- Primary opcode 19:
mcrf_2 = "4c000000XX",
isync_0 = "4c00012c",
crnor_3 = "4c000042CCC",
crnot_2 = "4c000042CC=",
crandc_3 = "4c000102CCC",
crxor_3 = "4c000182CCC",
crclr_1 = "4c000182C==",
crnand_3 = "4c0001c2CCC",
crand_3 = "4c000202CCC",
creqv_3 = "4c000242CCC",
crset_1 = "4c000242C==",
crorc_3 = "4c000342CCC",
cror_3 = "4c000382CCC",
crmove_2 = "4c000382CC=",
bclr_2 = "4c000020AA",
bclrl_2 = "4c000021AA",
bcctr_2 = "4c000420AA",
bcctrl_2 = "4c000421AA",
bctar_2 = "4c000460AA",
bctarl_2 = "4c000461AA",
blr_0 = "4e800020",
blrl_0 = "4e800021",
bctr_0 = "4e800420",
bctrl_0 = "4e800421",
-- Primary opcode 31:
cmpw_3 = "7c000000XRR",
cmpw_2 = "7c000000-RR",
cmpd_3 = "7c200000XRR",
cmpd_2 = "7c200000-RR",
tw_3 = "7c000008ARR",
lvsl_3 = "7c00000cVRR",
subfc_3 = "7c000010RRR.",
subc_3 = "7c000010RRR~.",
mulhdu_3 = "7c000012RRR.",
addc_3 = "7c000014RRR.",
mulhwu_3 = "7c000016RRR.",
isel_4 = "7c00001eRRRC",
isellt_3 = "7c00001eRRR",
iselgt_3 = "7c00005eRRR",
iseleq_3 = "7c00009eRRR",
mfcr_1 = "7c000026R",
mfocrf_2 = "7c100026RG",
mtcrf_2 = "7c000120GR",
mtocrf_2 = "7c100120GR",
lwarx_3 = "7c000028RR0R",
ldx_3 = "7c00002aRR0R",
lwzx_3 = "7c00002eRR0R",
slw_3 = "7c000030RR~R.",
cntlzw_2 = "7c000034RR~",
sld_3 = "7c000036RR~R.",
and_3 = "7c000038RR~R.",
cmplw_3 = "7c000040XRR",
cmplw_2 = "7c000040-RR",
cmpld_3 = "7c200040XRR",
cmpld_2 = "7c200040-RR",
lvsr_3 = "7c00004cVRR",
subf_3 = "7c000050RRR.",
sub_3 = "7c000050RRR~.",
lbarx_3 = "7c000068RR0R",
ldux_3 = "7c00006aRR0R",
dcbst_2 = "7c00006c-RR",
lwzux_3 = "7c00006eRR0R",
cntlzd_2 = "7c000074RR~",
andc_3 = "7c000078RR~R.",
td_3 = "7c000088ARR",
lvewx_3 = "7c00008eVRR",
mulhd_3 = "7c000092RRR.",
addg6s_3 = "7c000094RRR",
mulhw_3 = "7c000096RRR.",
dlmzb_3 = "7c00009cRR~R.",
ldarx_3 = "7c0000a8RR0R",
dcbf_2 = "7c0000ac-RR",
lbzx_3 = "7c0000aeRR0R",
lvx_3 = "7c0000ceVRR",
neg_2 = "7c0000d0RR.",
lharx_3 = "7c0000e8RR0R",
lbzux_3 = "7c0000eeRR0R",
popcntb_2 = "7c0000f4RR~",
not_2 = "7c0000f8RR~%.",
nor_3 = "7c0000f8RR~R.",
stvebx_3 = "7c00010eVRR",
subfe_3 = "7c000110RRR.",
sube_3 = "7c000110RRR~.",
adde_3 = "7c000114RRR.",
stdx_3 = "7c00012aRR0R",
["stwcx._3"] = "7c00012dRR0R.",
stwx_3 = "7c00012eRR0R",
prtyw_2 = "7c000134RR~",
stvehx_3 = "7c00014eVRR",
stdux_3 = "7c00016aRR0R",
["stqcx._3"] = "7c00016dR:R0R.",
stwux_3 = "7c00016eRR0R",
prtyd_2 = "7c000174RR~",
stvewx_3 = "7c00018eVRR",
subfze_2 = "7c000190RR.",
addze_2 = "7c000194RR.",
["stdcx._3"] = "7c0001adRR0R.",
stbx_3 = "7c0001aeRR0R",
stvx_3 = "7c0001ceVRR",
subfme_2 = "7c0001d0RR.",
mulld_3 = "7c0001d2RRR.",
addme_2 = "7c0001d4RR.",
mullw_3 = "7c0001d6RRR.",
dcbtst_2 = "7c0001ec-RR",
stbux_3 = "7c0001eeRR0R",
bpermd_3 = "7c0001f8RR~R",
lvepxl_3 = "7c00020eVRR",
add_3 = "7c000214RRR.",
lqarx_3 = "7c000228R:R0R",
dcbt_2 = "7c00022c-RR",
lhzx_3 = "7c00022eRR0R",
cdtbcd_2 = "7c000234RR~",
eqv_3 = "7c000238RR~R.",
lvepx_3 = "7c00024eVRR",
eciwx_3 = "7c00026cRR0R",
lhzux_3 = "7c00026eRR0R",
cbcdtd_2 = "7c000274RR~",
xor_3 = "7c000278RR~R.",
mfspefscr_1 = "7c0082a6R",
mfxer_1 = "7c0102a6R",
mflr_1 = "7c0802a6R",
mfctr_1 = "7c0902a6R",
lwax_3 = "7c0002aaRR0R",
lhax_3 = "7c0002aeRR0R",
mftb_1 = "7c0c42e6R",
mftbu_1 = "7c0d42e6R",
lvxl_3 = "7c0002ceVRR",
lwaux_3 = "7c0002eaRR0R",
lhaux_3 = "7c0002eeRR0R",
popcntw_2 = "7c0002f4RR~",
divdeu_3 = "7c000312RRR.",
divweu_3 = "7c000316RRR.",
sthx_3 = "7c00032eRR0R",
orc_3 = "7c000338RR~R.",
ecowx_3 = "7c00036cRR0R",
sthux_3 = "7c00036eRR0R",
or_3 = "7c000378RR~R.",
mr_2 = "7c000378RR~%.",
divdu_3 = "7c000392RRR.",
divwu_3 = "7c000396RRR.",
mtspefscr_1 = "7c0083a6R",
mtxer_1 = "7c0103a6R",
mtlr_1 = "7c0803a6R",
mtctr_1 = "7c0903a6R",
dcbi_2 = "7c0003ac-RR",
nand_3 = "7c0003b8RR~R.",
dsn_2 = "7c0003c6-RR",
stvxl_3 = "7c0003ceVRR",
divd_3 = "7c0003d2RRR.",
divw_3 = "7c0003d6RRR.",
popcntd_2 = "7c0003f4RR~",
cmpb_3 = "7c0003f8RR~R.",
mcrxr_1 = "7c000400X",
lbdx_3 = "7c000406RRR",
subfco_3 = "7c000410RRR.",
subco_3 = "7c000410RRR~.",
addco_3 = "7c000414RRR.",
ldbrx_3 = "7c000428RR0R",
lswx_3 = "7c00042aRR0R",
lwbrx_3 = "7c00042cRR0R",
lfsx_3 = "7c00042eFR0R",
srw_3 = "7c000430RR~R.",
srd_3 = "7c000436RR~R.",
lhdx_3 = "7c000446RRR",
subfo_3 = "7c000450RRR.",
subo_3 = "7c000450RRR~.",
lfsux_3 = "7c00046eFR0R",
lwdx_3 = "7c000486RRR",
lswi_3 = "7c0004aaRR0A",
sync_0 = "7c0004ac",
lwsync_0 = "7c2004ac",
ptesync_0 = "7c4004ac",
lfdx_3 = "7c0004aeFR0R",
lddx_3 = "7c0004c6RRR",
nego_2 = "7c0004d0RR.",
lfdux_3 = "7c0004eeFR0R",
stbdx_3 = "7c000506RRR",
subfeo_3 = "7c000510RRR.",
subeo_3 = "7c000510RRR~.",
addeo_3 = "7c000514RRR.",
stdbrx_3 = "7c000528RR0R",
stswx_3 = "7c00052aRR0R",
stwbrx_3 = "7c00052cRR0R",
stfsx_3 = "7c00052eFR0R",
sthdx_3 = "7c000546RRR",
["stbcx._3"] = "7c00056dRRR",
stfsux_3 = "7c00056eFR0R",
stwdx_3 = "7c000586RRR",
subfzeo_2 = "7c000590RR.",
addzeo_2 = "7c000594RR.",
stswi_3 = "7c0005aaRR0A",
["sthcx._3"] = "7c0005adRRR",
stfdx_3 = "7c0005aeFR0R",
stddx_3 = "7c0005c6RRR",
subfmeo_2 = "7c0005d0RR.",
mulldo_3 = "7c0005d2RRR.",
addmeo_2 = "7c0005d4RR.",
mullwo_3 = "7c0005d6RRR.",
dcba_2 = "7c0005ec-RR",
stfdux_3 = "7c0005eeFR0R",
stvepxl_3 = "7c00060eVRR",
addo_3 = "7c000614RRR.",
lhbrx_3 = "7c00062cRR0R",
lfdpx_3 = "7c00062eF:RR",
sraw_3 = "7c000630RR~R.",
srad_3 = "7c000634RR~R.",
lfddx_3 = "7c000646FRR",
stvepx_3 = "7c00064eVRR",
srawi_3 = "7c000670RR~A.",
sradi_3 = "7c000674RR~H.",
eieio_0 = "7c0006ac",
lfiwax_3 = "7c0006aeFR0R",
divdeuo_3 = "7c000712RRR.",
divweuo_3 = "7c000716RRR.",
sthbrx_3 = "7c00072cRR0R",
stfdpx_3 = "7c00072eF:RR",
extsh_2 = "7c000734RR~.",
stfddx_3 = "7c000746FRR",
divdeo_3 = "7c000752RRR.",
divweo_3 = "7c000756RRR.",
extsb_2 = "7c000774RR~.",
divduo_3 = "7c000792RRR.",
divwou_3 = "7c000796RRR.",
icbi_2 = "7c0007ac-RR",
stfiwx_3 = "7c0007aeFR0R",
extsw_2 = "7c0007b4RR~.",
divdo_3 = "7c0007d2RRR.",
divwo_3 = "7c0007d6RRR.",
dcbz_2 = "7c0007ec-RR",
["tbegin._1"] = "7c00051d1",
["tbegin._0"] = "7c00051d",
["tend._1"] = "7c00055dY",
["tend._0"] = "7c00055d",
["tendall._0"] = "7e00055d",
tcheck_1 = "7c00059cX",
["tsr._1"] = "7c0005dd1",
["tsuspend._0"] = "7c0005dd",
["tresume._0"] = "7c2005dd",
["tabortwc._3"] = "7c00061dARR",
["tabortdc._3"] = "7c00065dARR",
["tabortwci._3"] = "7c00069dARS",
["tabortdci._3"] = "7c0006ddARS",
["tabort._1"] = "7c00071d-R-",
["treclaim._1"] = "7c00075d-R",
["trechkpt._0"] = "7c0007dd",
lxsiwzx_3 = "7c000018QRR",
lxsiwax_3 = "7c000098QRR",
mfvsrd_2 = "7c000066-Rq",
mfvsrwz_2 = "7c0000e6-Rq",
stxsiwx_3 = "7c000118QRR",
mtvsrd_2 = "7c000166QR",
mtvsrwa_2 = "7c0001a6QR",
lxvdsx_3 = "7c000298QRR",
lxsspx_3 = "7c000418QRR",
lxsdx_3 = "7c000498QRR",
stxsspx_3 = "7c000518QRR",
stxsdx_3 = "7c000598QRR",
lxvw4x_3 = "7c000618QRR",
lxvd2x_3 = "7c000698QRR",
stxvw4x_3 = "7c000718QRR",
stxvd2x_3 = "7c000798QRR",
-- Primary opcode 30:
rldicl_4 = "78000000RR~HM.",
rldicr_4 = "78000004RR~HM.",
rldic_4 = "78000008RR~HM.",
rldimi_4 = "7800000cRR~HM.",
rldcl_4 = "78000010RR~RM.",
rldcr_4 = "78000012RR~RM.",
rotldi_3 = op_alias("rldicl_4", function(p)
p[4] = "0"
end),
rotrdi_3 = op_alias("rldicl_4", function(p)
p[3] = "64-("..p[3]..")"; p[4] = "0"
end),
rotld_3 = op_alias("rldcl_4", function(p)
p[4] = "0"
end),
sldi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"
end),
srdi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "64-("..p[3]..")"
end),
clrldi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "0"
end),
clrrdi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"; p[3] = "0"
end),
-- Primary opcode 56:
lq_2 = "e0000000R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 57:
lfdp_2 = "e4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 59:
fdivs_3 = "ec000024FFF.",
fsubs_3 = "ec000028FFF.",
fadds_3 = "ec00002aFFF.",
fsqrts_2 = "ec00002cF-F.",
fres_2 = "ec000030F-F.",
fmuls_3 = "ec000032FF-F.",
frsqrtes_2 = "ec000034F-F.",
fmsubs_4 = "ec000038FFFF~.",
fmadds_4 = "ec00003aFFFF~.",
fnmsubs_4 = "ec00003cFFFF~.",
fnmadds_4 = "ec00003eFFFF~.",
fcfids_2 = "ec00069cF-F.",
fcfidus_2 = "ec00079cF-F.",
dadd_3 = "ec000004FFF.",
dqua_4 = "ec000006FFFZ.",
dmul_3 = "ec000044FFF.",
drrnd_4 = "ec000046FFFZ.",
dscli_3 = "ec000084FF6.",
dquai_4 = "ec000086SF~FZ.",
dscri_3 = "ec0000c4FF6.",
drintx_4 = "ec0000c61F~FZ.",
dcmpo_3 = "ec000104XFF",
dtstex_3 = "ec000144XFF",
dtstdc_3 = "ec000184XF6",
dtstdg_3 = "ec0001c4XF6",
drintn_4 = "ec0001c61F~FZ.",
dctdp_2 = "ec000204F-F.",
dctfix_2 = "ec000244F-F.",
ddedpd_3 = "ec000284ZF~F.",
dxex_2 = "ec0002c4F-F.",
dsub_3 = "ec000404FFF.",
ddiv_3 = "ec000444FFF.",
dcmpu_3 = "ec000504XFF",
dtstsf_3 = "ec000544XFF",
drsp_2 = "ec000604F-F.",
dcffix_2 = "ec000644F-F.",
denbcd_3 = "ec000684YF~F.",
diex_3 = "ec0006c4FFF.",
-- Primary opcode 60:
xsaddsp_3 = "f0000000QQQ",
xsmaddasp_3 = "f0000008QQQ",
xxsldwi_4 = "f0000010QQQz",
xsrsqrtesp_2 = "f0000028Q-Q",
xssqrtsp_2 = "f000002cQ-Q",
xxsel_4 = "f0000030QQQQ",
xssubsp_3 = "f0000040QQQ",
xsmaddmsp_3 = "f0000048QQQ",
xxpermdi_4 = "f0000050QQQz",
xsresp_2 = "f0000068Q-Q",
xsmulsp_3 = "f0000080QQQ",
xsmsubasp_3 = "f0000088QQQ",
xxmrghw_3 = "f0000090QQQ",
xsdivsp_3 = "f00000c0QQQ",
xsmsubmsp_3 = "f00000c8QQQ",
xsadddp_3 = "f0000100QQQ",
xsmaddadp_3 = "f0000108QQQ",
xscmpudp_3 = "f0000118XQQ",
xscvdpuxws_2 = "f0000120Q-Q",
xsrdpi_2 = "f0000124Q-Q",
xsrsqrtedp_2 = "f0000128Q-Q",
xssqrtdp_2 = "f000012cQ-Q",
xssubdp_3 = "f0000140QQQ",
xsmaddmdp_3 = "f0000148QQQ",
xscmpodp_3 = "f0000158XQQ",
xscvdpsxws_2 = "f0000160Q-Q",
xsrdpiz_2 = "f0000164Q-Q",
xsredp_2 = "f0000168Q-Q",
xsmuldp_3 = "f0000180QQQ",
xsmsubadp_3 = "f0000188QQQ",
xxmrglw_3 = "f0000190QQQ",
xsrdpip_2 = "f00001a4Q-Q",
xstsqrtdp_2 = "f00001a8X-Q",
xsrdpic_2 = "f00001acQ-Q",
xsdivdp_3 = "f00001c0QQQ",
xsmsubmdp_3 = "f00001c8QQQ",
xsrdpim_2 = "f00001e4Q-Q",
xstdivdp_3 = "f00001e8XQQ",
xvaddsp_3 = "f0000200QQQ",
xvmaddasp_3 = "f0000208QQQ",
xvcmpeqsp_3 = "f0000218QQQ",
xvcvspuxws_2 = "f0000220Q-Q",
xvrspi_2 = "f0000224Q-Q",
xvrsqrtesp_2 = "f0000228Q-Q",
xvsqrtsp_2 = "f000022cQ-Q",
xvsubsp_3 = "f0000240QQQ",
xvmaddmsp_3 = "f0000248QQQ",
xvcmpgtsp_3 = "f0000258QQQ",
xvcvspsxws_2 = "f0000260Q-Q",
xvrspiz_2 = "f0000264Q-Q",
xvresp_2 = "f0000268Q-Q",
xvmulsp_3 = "f0000280QQQ",
xvmsubasp_3 = "f0000288QQQ",
xxspltw_3 = "f0000290QQg~",
xvcmpgesp_3 = "f0000298QQQ",
xvcvuxwsp_2 = "f00002a0Q-Q",
xvrspip_2 = "f00002a4Q-Q",
xvtsqrtsp_2 = "f00002a8X-Q",
xvrspic_2 = "f00002acQ-Q",
xvdivsp_3 = "f00002c0QQQ",
xvmsubmsp_3 = "f00002c8QQQ",
xvcvsxwsp_2 = "f00002e0Q-Q",
xvrspim_2 = "f00002e4Q-Q",
xvtdivsp_3 = "f00002e8XQQ",
xvadddp_3 = "f0000300QQQ",
xvmaddadp_3 = "f0000308QQQ",
xvcmpeqdp_3 = "f0000318QQQ",
xvcvdpuxws_2 = "f0000320Q-Q",
xvrdpi_2 = "f0000324Q-Q",
xvrsqrtedp_2 = "f0000328Q-Q",
xvsqrtdp_2 = "f000032cQ-Q",
xvsubdp_3 = "f0000340QQQ",
xvmaddmdp_3 = "f0000348QQQ",
xvcmpgtdp_3 = "f0000358QQQ",
xvcvdpsxws_2 = "f0000360Q-Q",
xvrdpiz_2 = "f0000364Q-Q",
xvredp_2 = "f0000368Q-Q",
xvmuldp_3 = "f0000380QQQ",
xvmsubadp_3 = "f0000388QQQ",
xvcmpgedp_3 = "f0000398QQQ",
xvcvuxwdp_2 = "f00003a0Q-Q",
xvrdpip_2 = "f00003a4Q-Q",
xvtsqrtdp_2 = "f00003a8X-Q",
xvrdpic_2 = "f00003acQ-Q",
xvdivdp_3 = "f00003c0QQQ",
xvmsubmdp_3 = "f00003c8QQQ",
xvcvsxwdp_2 = "f00003e0Q-Q",
xvrdpim_2 = "f00003e4Q-Q",
xvtdivdp_3 = "f00003e8XQQ",
xsnmaddasp_3 = "f0000408QQQ",
xxland_3 = "f0000410QQQ",
xscvdpsp_2 = "f0000424Q-Q",
xscvdpspn_2 = "f000042cQ-Q",
xsnmaddmsp_3 = "f0000448QQQ",
xxlandc_3 = "f0000450QQQ",
xsrsp_2 = "f0000464Q-Q",
xsnmsubasp_3 = "f0000488QQQ",
xxlor_3 = "f0000490QQQ",
xscvuxdsp_2 = "f00004a0Q-Q",
xsnmsubmsp_3 = "f00004c8QQQ",
xxlxor_3 = "f00004d0QQQ",
xscvsxdsp_2 = "f00004e0Q-Q",
xsmaxdp_3 = "f0000500QQQ",
xsnmaddadp_3 = "f0000508QQQ",
xxlnor_3 = "f0000510QQQ",
xscvdpuxds_2 = "f0000520Q-Q",
xscvspdp_2 = "f0000524Q-Q",
xscvspdpn_2 = "f000052cQ-Q",
xsmindp_3 = "f0000540QQQ",
xsnmaddmdp_3 = "f0000548QQQ",
xxlorc_3 = "f0000550QQQ",
xscvdpsxds_2 = "f0000560Q-Q",
xsabsdp_2 = "f0000564Q-Q",
xscpsgndp_3 = "f0000580QQQ",
xsnmsubadp_3 = "f0000588QQQ",
xxlnand_3 = "f0000590QQQ",
xscvuxddp_2 = "f00005a0Q-Q",
xsnabsdp_2 = "f00005a4Q-Q",
xsnmsubmdp_3 = "f00005c8QQQ",
xxleqv_3 = "f00005d0QQQ",
xscvsxddp_2 = "f00005e0Q-Q",
xsnegdp_2 = "f00005e4Q-Q",
xvmaxsp_3 = "f0000600QQQ",
xvnmaddasp_3 = "f0000608QQQ",
["xvcmpeqsp._3"] = "f0000618QQQ",
xvcvspuxds_2 = "f0000620Q-Q",
xvcvdpsp_2 = "f0000624Q-Q",
xvminsp_3 = "f0000640QQQ",
xvnmaddmsp_3 = "f0000648QQQ",
["xvcmpgtsp._3"] = "f0000658QQQ",
xvcvspsxds_2 = "f0000660Q-Q",
xvabssp_2 = "f0000664Q-Q",
xvcpsgnsp_3 = "f0000680QQQ",
xvnmsubasp_3 = "f0000688QQQ",
["xvcmpgesp._3"] = "f0000698QQQ",
xvcvuxdsp_2 = "f00006a0Q-Q",
xvnabssp_2 = "f00006a4Q-Q",
xvnmsubmsp_3 = "f00006c8QQQ",
xvcvsxdsp_2 = "f00006e0Q-Q",
xvnegsp_2 = "f00006e4Q-Q",
xvmaxdp_3 = "f0000700QQQ",
xvnmaddadp_3 = "f0000708QQQ",
["xvcmpeqdp._3"] = "f0000718QQQ",
xvcvdpuxds_2 = "f0000720Q-Q",
xvcvspdp_2 = "f0000724Q-Q",
xvmindp_3 = "f0000740QQQ",
xvnmaddmdp_3 = "f0000748QQQ",
["xvcmpgtdp._3"] = "f0000758QQQ",
xvcvdpsxds_2 = "f0000760Q-Q",
xvabsdp_2 = "f0000764Q-Q",
xvcpsgndp_3 = "f0000780QQQ",
xvnmsubadp_3 = "f0000788QQQ",
["xvcmpgedp._3"] = "f0000798QQQ",
xvcvuxddp_2 = "f00007a0Q-Q",
xvnabsdp_2 = "f00007a4Q-Q",
xvnmsubmdp_3 = "f00007c8QQQ",
xvcvsxddp_2 = "f00007e0Q-Q",
xvnegdp_2 = "f00007e4Q-Q",
-- Primary opcode 61:
stfdp_2 = "f4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 62:
stq_2 = "f8000002R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 63:
fdiv_3 = "fc000024FFF.",
fsub_3 = "fc000028FFF.",
fadd_3 = "fc00002aFFF.",
fsqrt_2 = "fc00002cF-F.",
fsel_4 = "fc00002eFFFF~.",
fre_2 = "fc000030F-F.",
fmul_3 = "fc000032FF-F.",
frsqrte_2 = "fc000034F-F.",
fmsub_4 = "fc000038FFFF~.",
fmadd_4 = "fc00003aFFFF~.",
fnmsub_4 = "fc00003cFFFF~.",
fnmadd_4 = "fc00003eFFFF~.",
fcmpu_3 = "fc000000XFF",
fcpsgn_3 = "fc000010FFF.",
fcmpo_3 = "fc000040XFF",
mtfsb1_1 = "fc00004cA",
fneg_2 = "fc000050F-F.",
mcrfs_2 = "fc000080XX",
mtfsb0_1 = "fc00008cA",
fmr_2 = "fc000090F-F.",
frsp_2 = "fc000018F-F.",
fctiw_2 = "fc00001cF-F.",
fctiwz_2 = "fc00001eF-F.",
ftdiv_2 = "fc000100X-F.",
fctiwu_2 = "fc00011cF-F.",
fctiwuz_2 = "fc00011eF-F.",
mtfsfi_2 = "fc00010cAA", -- NYI: upshift.
fnabs_2 = "fc000110F-F.",
ftsqrt_2 = "fc000140X-F.",
fabs_2 = "fc000210F-F.",
frin_2 = "fc000310F-F.",
friz_2 = "fc000350F-F.",
frip_2 = "fc000390F-F.",
frim_2 = "fc0003d0F-F.",
mffs_1 = "fc00048eF.",
-- NYI: mtfsf, mtfsb0, mtfsb1.
fctid_2 = "fc00065cF-F.",
fctidz_2 = "fc00065eF-F.",
fmrgow_3 = "fc00068cFFF",
fcfid_2 = "fc00069cF-F.",
fctidu_2 = "fc00075cF-F.",
fctiduz_2 = "fc00075eF-F.",
fmrgew_3 = "fc00078cFFF",
fcfidu_2 = "fc00079cF-F.",
daddq_3 = "fc000004F:F:F:.",
dquaq_4 = "fc000006F:F:F:Z.",
dmulq_3 = "fc000044F:F:F:.",
drrndq_4 = "fc000046F:F:F:Z.",
dscliq_3 = "fc000084F:F:6.",
dquaiq_4 = "fc000086SF:~F:Z.",
dscriq_3 = "fc0000c4F:F:6.",
drintxq_4 = "fc0000c61F:~F:Z.",
dcmpoq_3 = "fc000104XF:F:",
dtstexq_3 = "fc000144XF:F:",
dtstdcq_3 = "fc000184XF:6",
dtstdgq_3 = "fc0001c4XF:6",
drintnq_4 = "fc0001c61F:~F:Z.",
dctqpq_2 = "fc000204F:-F:.",
dctfixq_2 = "fc000244F:-F:.",
ddedpdq_3 = "fc000284ZF:~F:.",
dxexq_2 = "fc0002c4F:-F:.",
dsubq_3 = "fc000404F:F:F:.",
ddivq_3 = "fc000444F:F:F:.",
dcmpuq_3 = "fc000504XF:F:",
dtstsfq_3 = "fc000544XF:F:",
drdpq_2 = "fc000604F:-F:.",
dcffixq_2 = "fc000644F:-F:.",
denbcdq_3 = "fc000684YF:~F:.",
diexq_3 = "fc0006c4F:FF:.",
-- Primary opcode 4, SPE APU extension:
evaddw_3 = "10000200RRR",
evaddiw_3 = "10000202RAR~",
evsubw_3 = "10000204RRR~",
evsubiw_3 = "10000206RAR~",
evabs_2 = "10000208RR",
evneg_2 = "10000209RR",
evextsb_2 = "1000020aRR",
evextsh_2 = "1000020bRR",
evrndw_2 = "1000020cRR",
evcntlzw_2 = "1000020dRR",
evcntlsw_2 = "1000020eRR",
brinc_3 = "1000020fRRR",
evand_3 = "10000211RRR",
evandc_3 = "10000212RRR",
evxor_3 = "10000216RRR",
evor_3 = "10000217RRR",
evmr_2 = "10000217RR=",
evnor_3 = "10000218RRR",
evnot_2 = "10000218RR=",
eveqv_3 = "10000219RRR",
evorc_3 = "1000021bRRR",
evnand_3 = "1000021eRRR",
evsrwu_3 = "10000220RRR",
evsrws_3 = "10000221RRR",
evsrwiu_3 = "10000222RRA",
evsrwis_3 = "10000223RRA",
evslw_3 = "10000224RRR",
evslwi_3 = "10000226RRA",
evrlw_3 = "10000228RRR",
evsplati_2 = "10000229RS",
evrlwi_3 = "1000022aRRA",
evsplatfi_2 = "1000022bRS",
evmergehi_3 = "1000022cRRR",
evmergelo_3 = "1000022dRRR",
evcmpgtu_3 = "10000230XRR",
evcmpgtu_2 = "10000230-RR",
evcmpgts_3 = "10000231XRR",
evcmpgts_2 = "10000231-RR",
evcmpltu_3 = "10000232XRR",
evcmpltu_2 = "10000232-RR",
evcmplts_3 = "10000233XRR",
evcmplts_2 = "10000233-RR",
evcmpeq_3 = "10000234XRR",
evcmpeq_2 = "10000234-RR",
evsel_4 = "10000278RRRW",
evsel_3 = "10000278RRR",
evfsadd_3 = "10000280RRR",
evfssub_3 = "10000281RRR",
evfsabs_2 = "10000284RR",
evfsnabs_2 = "10000285RR",
evfsneg_2 = "10000286RR",
evfsmul_3 = "10000288RRR",
evfsdiv_3 = "10000289RRR",
evfscmpgt_3 = "1000028cXRR",
evfscmpgt_2 = "1000028c-RR",
evfscmplt_3 = "1000028dXRR",
evfscmplt_2 = "1000028d-RR",
evfscmpeq_3 = "1000028eXRR",
evfscmpeq_2 = "1000028e-RR",
evfscfui_2 = "10000290R-R",
evfscfsi_2 = "10000291R-R",
evfscfuf_2 = "10000292R-R",
evfscfsf_2 = "10000293R-R",
evfsctui_2 = "10000294R-R",
evfsctsi_2 = "10000295R-R",
evfsctuf_2 = "10000296R-R",
evfsctsf_2 = "10000297R-R",
evfsctuiz_2 = "10000298R-R",
evfsctsiz_2 = "1000029aR-R",
evfststgt_3 = "1000029cXRR",
evfststgt_2 = "1000029c-RR",
evfststlt_3 = "1000029dXRR",
evfststlt_2 = "1000029d-RR",
evfststeq_3 = "1000029eXRR",
evfststeq_2 = "1000029e-RR",
efsadd_3 = "100002c0RRR",
efssub_3 = "100002c1RRR",
efsabs_2 = "100002c4RR",
efsnabs_2 = "100002c5RR",
efsneg_2 = "100002c6RR",
efsmul_3 = "100002c8RRR",
efsdiv_3 = "100002c9RRR",
efscmpgt_3 = "100002ccXRR",
efscmpgt_2 = "100002cc-RR",
efscmplt_3 = "100002cdXRR",
efscmplt_2 = "100002cd-RR",
efscmpeq_3 = "100002ceXRR",
efscmpeq_2 = "100002ce-RR",
efscfd_2 = "100002cfR-R",
efscfui_2 = "100002d0R-R",
efscfsi_2 = "100002d1R-R",
efscfuf_2 = "100002d2R-R",
efscfsf_2 = "100002d3R-R",
efsctui_2 = "100002d4R-R",
efsctsi_2 = "100002d5R-R",
efsctuf_2 = "100002d6R-R",
efsctsf_2 = "100002d7R-R",
efsctuiz_2 = "100002d8R-R",
efsctsiz_2 = "100002daR-R",
efststgt_3 = "100002dcXRR",
efststgt_2 = "100002dc-RR",
efststlt_3 = "100002ddXRR",
efststlt_2 = "100002dd-RR",
efststeq_3 = "100002deXRR",
efststeq_2 = "100002de-RR",
efdadd_3 = "100002e0RRR",
efdsub_3 = "100002e1RRR",
efdcfuid_2 = "100002e2R-R",
efdcfsid_2 = "100002e3R-R",
efdabs_2 = "100002e4RR",
efdnabs_2 = "100002e5RR",
efdneg_2 = "100002e6RR",
efdmul_3 = "100002e8RRR",
efddiv_3 = "100002e9RRR",
efdctuidz_2 = "100002eaR-R",
efdctsidz_2 = "100002ebR-R",
efdcmpgt_3 = "100002ecXRR",
efdcmpgt_2 = "100002ec-RR",
efdcmplt_3 = "100002edXRR",
efdcmplt_2 = "100002ed-RR",
efdcmpeq_3 = "100002eeXRR",
efdcmpeq_2 = "100002ee-RR",
efdcfs_2 = "100002efR-R",
efdcfui_2 = "100002f0R-R",
efdcfsi_2 = "100002f1R-R",
efdcfuf_2 = "100002f2R-R",
efdcfsf_2 = "100002f3R-R",
efdctui_2 = "100002f4R-R",
efdctsi_2 = "100002f5R-R",
efdctuf_2 = "100002f6R-R",
efdctsf_2 = "100002f7R-R",
efdctuiz_2 = "100002f8R-R",
efdctsiz_2 = "100002faR-R",
efdtstgt_3 = "100002fcXRR",
efdtstgt_2 = "100002fc-RR",
efdtstlt_3 = "100002fdXRR",
efdtstlt_2 = "100002fd-RR",
efdtsteq_3 = "100002feXRR",
efdtsteq_2 = "100002fe-RR",
evlddx_3 = "10000300RR0R",
evldd_2 = "10000301R8",
evldwx_3 = "10000302RR0R",
evldw_2 = "10000303R8",
evldhx_3 = "10000304RR0R",
evldh_2 = "10000305R8",
evlwhex_3 = "10000310RR0R",
evlwhe_2 = "10000311R4",
evlwhoux_3 = "10000314RR0R",
evlwhou_2 = "10000315R4",
evlwhosx_3 = "10000316RR0R",
evlwhos_2 = "10000317R4",
evstddx_3 = "10000320RR0R",
evstdd_2 = "10000321R8",
evstdwx_3 = "10000322RR0R",
evstdw_2 = "10000323R8",
evstdhx_3 = "10000324RR0R",
evstdh_2 = "10000325R8",
evstwhex_3 = "10000330RR0R",
evstwhe_2 = "10000331R4",
evstwhox_3 = "10000334RR0R",
evstwho_2 = "10000335R4",
evstwwex_3 = "10000338RR0R",
evstwwe_2 = "10000339R4",
evstwwox_3 = "1000033cRR0R",
evstwwo_2 = "1000033dR4",
evmhessf_3 = "10000403RRR",
evmhossf_3 = "10000407RRR",
evmheumi_3 = "10000408RRR",
evmhesmi_3 = "10000409RRR",
evmhesmf_3 = "1000040bRRR",
evmhoumi_3 = "1000040cRRR",
evmhosmi_3 = "1000040dRRR",
evmhosmf_3 = "1000040fRRR",
evmhessfa_3 = "10000423RRR",
evmhossfa_3 = "10000427RRR",
evmheumia_3 = "10000428RRR",
evmhesmia_3 = "10000429RRR",
evmhesmfa_3 = "1000042bRRR",
evmhoumia_3 = "1000042cRRR",
evmhosmia_3 = "1000042dRRR",
evmhosmfa_3 = "1000042fRRR",
evmwhssf_3 = "10000447RRR",
evmwlumi_3 = "10000448RRR",
evmwhumi_3 = "1000044cRRR",
evmwhsmi_3 = "1000044dRRR",
evmwhsmf_3 = "1000044fRRR",
evmwssf_3 = "10000453RRR",
evmwumi_3 = "10000458RRR",
evmwsmi_3 = "10000459RRR",
evmwsmf_3 = "1000045bRRR",
evmwhssfa_3 = "10000467RRR",
evmwlumia_3 = "10000468RRR",
evmwhumia_3 = "1000046cRRR",
evmwhsmia_3 = "1000046dRRR",
evmwhsmfa_3 = "1000046fRRR",
evmwssfa_3 = "10000473RRR",
evmwumia_3 = "10000478RRR",
evmwsmia_3 = "10000479RRR",
evmwsmfa_3 = "1000047bRRR",
evmra_2 = "100004c4RR",
evdivws_3 = "100004c6RRR",
evdivwu_3 = "100004c7RRR",
evmwssfaa_3 = "10000553RRR",
evmwumiaa_3 = "10000558RRR",
evmwsmiaa_3 = "10000559RRR",
evmwsmfaa_3 = "1000055bRRR",
evmwssfan_3 = "100005d3RRR",
evmwumian_3 = "100005d8RRR",
evmwsmian_3 = "100005d9RRR",
evmwsmfan_3 = "100005dbRRR",
evmergehilo_3 = "1000022eRRR",
evmergelohi_3 = "1000022fRRR",
evlhhesplatx_3 = "10000308RR0R",
evlhhesplat_2 = "10000309R2",
evlhhousplatx_3 = "1000030cRR0R",
evlhhousplat_2 = "1000030dR2",
evlhhossplatx_3 = "1000030eRR0R",
evlhhossplat_2 = "1000030fR2",
evlwwsplatx_3 = "10000318RR0R",
evlwwsplat_2 = "10000319R4",
evlwhsplatx_3 = "1000031cRR0R",
evlwhsplat_2 = "1000031dR4",
evaddusiaaw_2 = "100004c0RR",
evaddssiaaw_2 = "100004c1RR",
evsubfusiaaw_2 = "100004c2RR",
evsubfssiaaw_2 = "100004c3RR",
evaddumiaaw_2 = "100004c8RR",
evaddsmiaaw_2 = "100004c9RR",
evsubfumiaaw_2 = "100004caRR",
evsubfsmiaaw_2 = "100004cbRR",
evmheusiaaw_3 = "10000500RRR",
evmhessiaaw_3 = "10000501RRR",
evmhessfaaw_3 = "10000503RRR",
evmhousiaaw_3 = "10000504RRR",
evmhossiaaw_3 = "10000505RRR",
evmhossfaaw_3 = "10000507RRR",
evmheumiaaw_3 = "10000508RRR",
evmhesmiaaw_3 = "10000509RRR",
evmhesmfaaw_3 = "1000050bRRR",
evmhoumiaaw_3 = "1000050cRRR",
evmhosmiaaw_3 = "1000050dRRR",
evmhosmfaaw_3 = "1000050fRRR",
evmhegumiaa_3 = "10000528RRR",
evmhegsmiaa_3 = "10000529RRR",
evmhegsmfaa_3 = "1000052bRRR",
evmhogumiaa_3 = "1000052cRRR",
evmhogsmiaa_3 = "1000052dRRR",
evmhogsmfaa_3 = "1000052fRRR",
evmwlusiaaw_3 = "10000540RRR",
evmwlssiaaw_3 = "10000541RRR",
evmwlumiaaw_3 = "10000548RRR",
evmwlsmiaaw_3 = "10000549RRR",
evmheusianw_3 = "10000580RRR",
evmhessianw_3 = "10000581RRR",
evmhessfanw_3 = "10000583RRR",
evmhousianw_3 = "10000584RRR",
evmhossianw_3 = "10000585RRR",
evmhossfanw_3 = "10000587RRR",
evmheumianw_3 = "10000588RRR",
evmhesmianw_3 = "10000589RRR",
evmhesmfanw_3 = "1000058bRRR",
evmhoumianw_3 = "1000058cRRR",
evmhosmianw_3 = "1000058dRRR",
evmhosmfanw_3 = "1000058fRRR",
evmhegumian_3 = "100005a8RRR",
evmhegsmian_3 = "100005a9RRR",
evmhegsmfan_3 = "100005abRRR",
evmhogumian_3 = "100005acRRR",
evmhogsmian_3 = "100005adRRR",
evmhogsmfan_3 = "100005afRRR",
evmwlusianw_3 = "100005c0RRR",
evmwlssianw_3 = "100005c1RRR",
evmwlumianw_3 = "100005c8RRR",
evmwlsmianw_3 = "100005c9RRR",
-- NYI: Book E instructions.
}
-- Add mnemonics for "." variants.
do
local t = {}
for k,v in pairs(map_op) do
if type(v) == "string" and sub(v, -1) == "." then
local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2)
t[sub(k, 1, -3).."."..sub(k, -2)] = v2
end
end
for k,v in pairs(t) do
map_op[k] = v
end
end
-- Add more branch mnemonics.
for cond,c in pairs(map_cond) do
local b1 = "b"..cond
local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0)
-- bX[l]
map_op[b1.."_1"] = tohex(0x40800000 + c1).."K"
map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K"
map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K"
map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK"
map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK"
map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK"
-- bXlr[l]
map_op[b1.."lr_0"] = tohex(0x4c800020 + c1)
map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1)
map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1)
map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1)
-- bXctr[l]
map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X"
map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X"
map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X"
map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X"
end
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^r([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_fpr(expr)
local r = match(expr, "^f([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vr(expr)
local r = match(expr, "^v([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vs(expr)
local r = match(expr, "^vs([1-6]?[0-9])$")
if r then
r = tonumber(r)
if r <= 63 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_cr(expr)
local r = match(expr, "^cr([0-7])$")
if r then return tonumber(r) end
werror("bad condition register name `"..expr.."'")
end
local function parse_cond(expr)
local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$")
if r then
r = tonumber(r)
local c = map_cond[cond]
if c and c < 4 then return r*4+c end
end
werror("bad condition bit name `"..expr.."'")
end
local parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^[rfv]([1-3]?[0-9])$") or
match(imm, "^vs([1-6]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_shiftmask(imm, isshift)
local n = parse_number(imm)
if n then
if shr(n, 6) == 0 then
local lsb = band(n, 31)
local msb = n - lsb
return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb)
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^r([1-3]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction("IMMSH", isshift and 1 or 0, imm)
return 0;
end
end
local function parse_disp(disp)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 16, 0, 0, true)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_u5disp(disp, scale)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 5, 11, scale, false)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
op_template = function(params, template, nparams)
if not params then return sub(template, 9) end
local op = tonumber(sub(template, 1, 8), 16)
local n, rs = 1, 26
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions (rlwinm).
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
if p == "R" then
rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1
elseif p == "F" then
rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1
elseif p == "V" then
rs = rs - 5; op = op + shl(parse_vr(params[n]), rs); n = n + 1
elseif p == "Q" then
local vs = parse_vs(params[n]); n = n + 1; rs = rs - 5
local sh = rs == 6 and 2 or 3 + band(shr(rs, 1), 3)
op = op + shl(band(vs, 31), rs) + shr(band(vs, 32), sh)
elseif p == "q" then
local vs = parse_vs(params[n]); n = n + 1
op = op + shl(band(vs, 31), 21) + shr(band(vs, 32), 5)
elseif p == "A" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1
elseif p == "S" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1
elseif p == "I" then
op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1
elseif p == "U" then
op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1
elseif p == "D" then
op = op + parse_disp(params[n]); n = n + 1
elseif p == "2" then
op = op + parse_u5disp(params[n], 1); n = n + 1
elseif p == "4" then
op = op + parse_u5disp(params[n], 2); n = n + 1
elseif p == "8" then
op = op + parse_u5disp(params[n], 3); n = n + 1
elseif p == "C" then
rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1
elseif p == "X" then
rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1
elseif p == "1" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs, 0, false); n = n + 1
elseif p == "g" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs, 0, false); n = n + 1
elseif p == "3" then
rs = rs - 5; op = op + parse_imm(params[n], 3, rs, 0, false); n = n + 1
elseif p == "P" then
rs = rs - 5; op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "p" then
op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "6" then
rs = rs - 6; op = op + parse_imm(params[n], 6, rs, 0, false); n = n + 1
elseif p == "Y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+4, 0, false); n = n + 1
elseif p == "y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+3, 0, false); n = n + 1
elseif p == "Z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+3, 0, false); n = n + 1
elseif p == "z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+2, 0, false); n = n + 1
elseif p == "W" then
op = op + parse_cr(params[n]); n = n + 1
elseif p == "G" then
op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1
elseif p == "H" then
op = op + parse_shiftmask(params[n], true); n = n + 1
elseif p == "M" then
op = op + parse_shiftmask(params[n], false); n = n + 1
elseif p == "J" or p == "K" then
local mode, n, s = parse_label(params[n], false)
if p == "K" then n = n + 2048 end
waction("REL_"..mode, n, s, 1)
n = n + 1
elseif p == "0" then
if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end
elseif p == "=" or p == "%" then
local t = band(shr(op, p == "%" and rs+5 or rs), 31)
rs = rs - 5
op = op + shl(t, rs)
elseif p == "~" then
local mm = shl(31, rs)
local lo = band(op, mm)
local hi = band(op, shl(mm, 5))
op = op - lo - hi + shl(lo, 5) + shr(hi, 5)
elseif p == ":" then
if band(shr(op, rs), 1) ~= 0 then werror("register pair expected") end
elseif p == "-" then
rs = rs - 5
elseif p == "." then
-- Ignored.
else
assert(false)
end
end
wputpos(pos, op)
end
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| mit |
victorperin/tibia-server | data/actions/scripts/inquisition quest/inquisitionQuestHolyWater.lua | 1 | 3068 | local pos = {x=32260,y=32791,z =7}
local time = 10
local function OpenDoor()
return (doTransformItem(getTileItemById( pos,8696 ).uid, 8697))
end
local function transformBack1()
return (doTransformItem(getTileItemById( {x=33115,y=31702,z =12},8754).uid, 8755))
end
local function transformBack2()
return (doTransformItem(getTileItemById( {x=33115,y=31702,z =12},8756).uid, 8757))
end
local function transformBack3()
return (doTransformItem(getTileItemById( {x=33115,y=31702,z =12},8758).uid, 8759))
end
local function transformBack4()
return (doTransformItem(getTileItemById( {x=33115,y=31702,z =12},8759).uid, 8753))
end
function onUse(cid, item, fromPosition, itemEx, toPosition)
-- Eclipse
if(itemEx.actionid == 2000) then
doRemoveItem(item.uid, 1)
doSendMagicEffect(toPosition, CONST_ME_FIREAREA)
setPlayerStorageValue(cid, Storage.TheInquisition.Questline, 5)
Player(cid):setStorageValue(Storage.TheInquisition.Mission02, 2) -- The Inquisition Questlog- "Mission 2: Eclipse"
end
-- Haunted Ruin
if(itemEx.actionid == 2003) then
if(getPlayerStorageValue(cid, Storage.TheInquisition.Questline) == 12) then
doSummonCreature("Pirate Ghost", toPosition)
doRemoveItem(item.uid, 1)
setPlayerStorageValue(cid, Storage.TheInquisition.Questline, 13)
Player(cid):setStorageValue(Storage.TheInquisition.Mission04, 2) -- The Inquisition Questlog- "Mission 4: The Haunted Ruin"
doTransformItem(getTileItemById( pos,8697 ).uid, 8696)
addEvent(OpenDoor, 10*1000)
end
end
-- Shadow Nexus
if(itemEx.itemid == 8753) then
doTransformItem(itemEx.uid, 8754)
addEvent(transformBack1, time*1000)
doCreatureSay(cid,""..getCreatureName(cid).." damaged the shadow nexus! You can't damage it while it's burning.",TALKTYPE_MONSTER_YELL, false, cid, getThingPos(itemEx.uid))
elseif(itemEx.itemid == 8755) then
doTransformItem(itemEx.uid, 8756)
addEvent(transformBack2, time*1000)
doCreatureSay(cid,""..getCreatureName(cid).." damaged the shadow nexus! You can't damage it while it's burning.",TALKTYPE_MONSTER_YELL, false, cid, getThingPos(itemEx.uid))
elseif(itemEx.itemid == 8757) then
doTransformItem(itemEx.uid, 8758)
addEvent(transformBack3, time*1000)
doCreatureSay(cid,""..getCreatureName(cid).." damaged the shadow nexus! You can't damage it while it's burning.",TALKTYPE_MONSTER_YELL, false, cid, getThingPos(itemEx.uid))
elseif(itemEx.itemid == 8759) then
if(getGlobalStorageValue(210) < 1) then
addEvent(setGlobalStorageValue, 20 * 1000, 210, 0)
end
if(getPlayerStorageValue(cid, Storage.TheInquisition.Questline) < 22) then
setPlayerStorageValue(cid, Storage.TheInquisition.Questline, 22)
Player(cid):setStorageValue(Storage.TheInquisition.Mission07, 2) -- The Inquisition Questlog- "Mission 7: The Shadow Nexus"
end
doCreatureSay(cid,""..getCreatureName(cid).." destroyed the shadow nexus! In 20 seconds it will return to its original state.",TALKTYPE_MONSTER_YELL, false, cid, getThingPos(itemEx.uid))
doRemoveItem(item.uid, 1)
addEvent(transformBack4, 60*1000)
end
return true
end | apache-2.0 |
CrazyEddieTK/Zero-K | effects/nuke_150.lua | 25 | 15829 | -- nuke_150_seacloud
-- nuke_150_landcloud_ring
-- nuke_150_landcloud
-- nuke_150_landcloud_topcap
-- nuke_150_landcloud_cap
-- nuke_150_seacloud_topcap
-- nuke_150_seacloud_ring
-- nuke_150
-- nuke_150_seacloud_cap
-- nuke_150_seacloud_pillar
-- nuke_150_landcloud_pillar
return {
["nuke_150_seacloud"] = {
usedefaultexplosions = false,
cap = {
air = true,
class = [[CExpGenSpawner]],
count = 24,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_SEACLOUD_CAP]],
pos = [[0, i8, 0]],
},
},
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 32,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_SEACLOUD_PILLAR]],
pos = [[0, i8, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = 16,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_SEACLOUD_RING]],
pos = [[0, 128, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 8,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[24 i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_SEACLOUD_TOPCAP]],
pos = [[0, 192 i8, 0]],
},
},
},
["nuke_150_landcloud_ring"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0.75 1 1 0.75 0.5 1 0.75 0.75 0.75 1 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 128,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 8,
sizemod = 0.5,
texture = [[smokesmall]],
},
},
},
["nuke_150_landcloud"] = {
usedefaultexplosions = false,
cap = {
air = true,
class = [[CExpGenSpawner]],
count = 24,
ground = true,
water = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_LANDCLOUD_CAP]],
pos = [[0, i8, 0]],
},
},
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 32,
ground = true,
water = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_LANDCLOUD_PILLAR]],
pos = [[0, i8, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 16,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_LANDCLOUD_RING]],
pos = [[0, 128, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 8,
ground = true,
water = true,
properties = {
delay = [[24 i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_LANDCLOUD_TOPCAP]],
pos = [[0, 192 i8, 0]],
},
},
},
["nuke_150_landcloud_topcap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[fireball]],
},
},
},
["nuke_150_landcloud_cap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 15,
particlelifespread = 5,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[fireball]],
},
},
},
["nuke_150_seacloud_topcap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_150_seacloud_ring"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 128,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 8,
sizemod = 0.5,
texture = [[smokesmall]],
},
},
},
["nuke_150"] = {
usedefaultexplosions = false,
groundflash = {
alwaysvisible = true,
circlealpha = 1,
circlegrowth = 10,
flashalpha = 0.5,
flashsize = 150,
ttl = 15,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0,
},
},
landcloud = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
properties = {
delay = 15,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_LANDCLOUD]],
pos = [[0, 0, 0]],
},
},
landdirt = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.95,
alwaysvisible = true,
colormap = [[0 0 0 0 0.5 0.4 0.3 1 0.6 0.4 0.2 0.75 0.5 0.4 0.3 0.5 0 0 0 0]],
directional = false,
emitrot = 85,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.1, 0]],
numparticles = 64,
particlelife = 30,
particlelifespread = 5,
particlesize = 4,
particlesizespread = 4,
particlespeed = 2,
particlespeedspread = 12,
pos = [[0, 0, 0]],
sizegrowth = 8,
sizemod = 0.75,
texture = [[dirt]],
},
},
pikes = {
air = true,
class = [[explspike]],
count = 32,
ground = true,
water = true,
properties = {
alpha = 1,
alphadecay = 0.025,
alwaysvisible = true,
color = [[1,0.5,0.1]],
dir = [[-8 r16, -8 r16, -8 r16]],
length = 1,
lengthgrowth = 1,
width = 64,
},
},
seacloud = {
class = [[CExpGenSpawner]],
count = 1,
water = true,
underwater = true,
properties = {
delay = 15,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_150_SEACLOUD]],
pos = [[0, 0, 0]],
},
},
sphere = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alpha = 0.5,
color = [[1,1,0.5]],
expansionspeed = 15,
ttl = 20,
},
},
watermist = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
underwater = true,
properties = {
airdrag = 0.99,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.2, 0]],
numparticles = 16,
particlelife = 30,
particlelifespread = 5,
particlesize = 4,
particlesizespread = 4,
particlespeed = 6,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 4,
sizemod = 1,
texture = [[smokesmall]],
},
},
},
["nuke_150_seacloud_cap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 15,
particlelifespread = 5,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_150_seacloud_pillar"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_150_landcloud_pillar"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0.5 1 1 0.75 0.5 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 60,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 4,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 16,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
}
| gpl-2.0 |
CrazyEddieTK/Zero-K | gamedata/modularcomms/weapons/shockrifle.lua | 5 | 1078 | local name = "commweapon_shockrifle"
local weaponDef = {
name = [[Shock Rifle]],
areaOfEffect = 16,
colormap = [[0 0 0 0 0 0 0.2 0.2 0 0 0.5 0.5 0 0 0.7 0.7 0 0 1 1 0 0 1 1]],
craterBoost = 0,
craterMult = 0,
customParams = {
slot = [[5]],
light_radius = 0,
},
damage = {
default = 1500,
subs = 75,
},
explosionGenerator = [[custom:spectre_hit]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 600,
reloadtime = 12,
rgbColor = [[1 0.2 0.2]],
separation = 0.5,
size = 5,
sizeDecay = 0,
soundHit = [[weapon/laser/heavy_laser6]],
soundStart = [[weapon/gauss_fire]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 1000,
}
return name, weaponDef
| gpl-2.0 |
Evengard/UniMod | lua/funcs.lua | 1 | 3287 | mapMode=function()
local gf=gameFlags()
gf=bitAnd(gf, 0x00001FF0)
if bitAnd(gf, 0x100)>0 then
return "arena"
elseif bitAnd(gf, 0x400)>0 then
return "elimination"
elseif bitAnd(gf, 0x20)>0 then
return "ctf"
elseif bitAnd(gf,0x80)>0 then
return "chat"
elseif bitAnd(gf, 0x10)>0 then
return "kotr"
elseif bitAnd(gf, 0x40)>0 then
return "flagball"
end
return "unknown"
end
getPlayerList=function()
local result={}
for q,v in pairs(playerList())
do
table.insert(result,playerInfo(v))
end
return result
end
getServerInfo=function()
return {map=mapGetName(), mode=mapMode(), playerList=getPlayerList()}
end
function getPlayerCountInGame()
local c=getPlayerList()
local ingame=0
for i,q in pairs(c) do
if q.isObserver==0 then
ingame=ingame+1
end
end
return ingame
end
function math.logb(number, base)
return math.log10(number) / math.log10(base);
end;
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end;
function string.bin_get(str, index)
return str:byte(index);
end;
function string.bin_set(str, index, value)
local before = "";
if index > 1 then
before = str:sub(1, index-1);
end;
local after = "";
if index < str:len() then
after = str:sub(index+1, str:len());
end;
str = before..string.char(value)..after
return str;
end;
bin_ops = {};
function bin_ops.number_memsize(number)
local size = 0;
local trim = math.floor;
if number < 0 then
trim = math.ceil;
end;
while number ~= 0 do
size = size + 1;
number = trim(number / 256);
end;
return size;
end;
function bin_ops.to_number(bin_str, size, offset)
offset = offset or 1;
local maxsize = bin_str:len();
local warn_truncate = false;
if maxsize > 7 then
maxsize = 7; -- Lua allows only up to 7 bytes integers
warn_truncate = true;
end;
size = size or maxsize;
if size > maxsize then
if warn_truncate then
print("Data truncated due to overflow!");
end;
size = maxsize;
end;
local number = 0;
local shiftmod = 0;
for i=offset, offset+size-1, 1 do
local value = bin_str:bin_get(i);
value = value * 2 ^ (8 * shiftmod);
number = number + value;
shiftmod = shiftmod + 1;
end;
return number;
end;
function bin_ops.to_string(number, bytes)
local stored_bytes = bin_ops.number_memsize(number);
bytes = bytes or stored_bytes;
if bytes > 7 then
bytes = stored_bytes;
end;
local trim = math.floor;
local is_negative = false;
if number < 0 then
trim = math.ceil;
is_negative = true;
end;
local bin_str = "";
local divider = 1;
for i = 0, bytes-1, 1 do
number = trim(number / divider);
local byte_data = number % 256;
if byte_data == 0 and is_negative == true then
byte_data = 0xFF;
end;
bin_str = bin_str..string.char(byte_data);
divider = 256;
end;
return bin_str;
end;
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end | lgpl-3.0 |
timroes/awesome | lib/awful/layout/suit/max.lua | 3 | 1410 | ---------------------------------------------------------------------------
--- Maximized and fullscreen layouts module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @module awful.layout
---------------------------------------------------------------------------
-- Grab environment we need
local pairs = pairs
local max = {}
--- The max layout layoutbox icon.
-- @beautiful beautiful.layout_max
-- @param surface
-- @see gears.surface
--- The fullscreen layout layoutbox icon.
-- @beautiful beautiful.layout_fullscreen
-- @param surface
-- @see gears.surface
local function fmax(p, fs)
-- Fullscreen?
local area
if fs then
area = p.geometry
else
area = p.workarea
end
for _, c in pairs(p.clients) do
local g = {
x = area.x,
y = area.y,
width = area.width,
height = area.height
}
p.geometries[c] = g
end
end
--- Maximized layout.
-- @clientlayout awful.layout.suit.max.name
max.name = "max"
function max.arrange(p)
return fmax(p, false)
end
--- Fullscreen layout.
-- @clientlayout awful.layout.suit.max.fullscreen
max.fullscreen = {}
max.fullscreen.name = "fullscreen"
function max.fullscreen.arrange(p)
return fmax(p, true)
end
return max
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
minetest-games/Minetest_TNG | mods/default/lua/nodes/glass.lua | 2 | 1225 | -- mods/default/lua/nodes/glass.lua
-- ================================
-- See README.txt for licensing and other information.
default.register_node("default:glass", {
description = "Glass",
drawtype = "glasslike_framed_optional",
tiles = {"default_glass.png", "default_glass_detail.png"},
inventory_image = minetest.inventorycube("default_glass.png"),
paramtype = "light",
sunlight_propagates = true,
is_ground_content = false,
groups = {cracky = 3, oddly_breakable_by_hand = 3},
sounds = default.node_sound_glass_defaults(),
})
default.register_node("default:obsidian_glass", {
description = "Obsidian Glass",
drawtype = "glasslike_framed_optional",
tiles = {"default_obsidian_glass.png", "default_obsidian_glass_detail.png"},
inventory_image = minetest.inventorycube("default_obsidian_glass.png"),
paramtype = "light",
is_ground_content = false,
sunlight_propagates = true,
sounds = default.node_sound_glass_defaults(),
groups = {cracky = 3, oddly_breakable_by_hand = 3},
})
-- Crafting
core.register_craft({
type = "cooking",
output = "default:glass",
recipe = "group:sand",
})
core.register_craft({
type = "cooking",
output = "default:obsidian_glass",
recipe = "default:obsidian_shard",
})
| gpl-3.0 |
czfshine/Don-t-Starve | data/scripts/map/rooms/terrain_mazes.lua | 1 | 1148 |
AddRoom("LabyrinthGuarden", {
colour={r=0.3,g=0.2,b=0.1,a=0.3},
value = GROUND.BRICK,
tags = {"LabyrinthEntrance"},
contents = {
countstaticlayouts =
{
["WalledGarden"] = 1,
},
},
})
AddRoom("BGLabyrinth", {
colour={r=0.3,g=0.2,b=0.1,a=0.3},
value = GROUND.CAVE_NOISE,
tags = {"Labyrinth"},
contents = {
distributepercent = .04,
distributeprefabs=
{
nightmarelight = .45,
dropperweb = 1,
}
}
})
AddRoom("BGMaze", {
colour={r=0.3,g=0.2,b=0.1,a=0.3},
value = GROUND.MUD,
tags = {"Maze"},
contents = {
distributepercent = 0.15,
distributeprefabs=
{
lichen = .001,
cave_fern = .0015,
--pond_cave = .002,
pillar_algae = .0001,
slurper = .0002,
}
}
})
| gpl-2.0 |
CrazyEddieTK/Zero-K | units/droneheavyslow.lua | 5 | 3367 | unitDef = {
unitname = [[droneheavyslow]],
name = [[Viper]],
description = [[Advanced Battle Drone]],
acceleration = 0.3,
airHoverFactor = 4,
brakeRate = 0.24,
buildCostMetal = 35,
builder = false,
buildPic = [[droneheavyslow.png]],
canBeAssisted = false,
canFly = true,
canGuard = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
category = [[GUNSHIP]],
collide = false,
cruiseAlt = 100,
explodeAs = [[TINY_BUILDINGEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
hoverAttack = true,
iconType = [[gunship]],
maxDamage = 430,
maxVelocity = 5,
minCloakDistance = 75,
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE SUB]],
objectName = [[battledrone.s3o]],
reclaimable = false,
script = [[droneheavyslow.lua]],
selfDestructAs = [[TINY_BUILDINGEX]],
customParams = {
is_drone = 1,
},
sfxtypes = {
explosiongenerators = {
},
},
sightDistance = 500,
turnRate = 792,
upright = true,
weapons = {
{
def = [[DISRUPTOR]],
badTargetCategory = [[FIXEDWING]],
mainDir = [[0 0 1]],
maxAngleDif = 20,
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
DISRUPTOR = {
name = [[Disruptor Pulse Beam]],
areaOfEffect = 24,
beamdecay = 0.9,
beamTime = 1/30,
beamttl = 50,
coreThickness = 0.25,
craterBoost = 0,
craterMult = 0,
customParams = {
timeslow_damagefactor = [[2]],
light_camera_height = 2000,
light_color = [[0.85 0.33 1]],
light_radius = 150,
},
damage = {
default = 200,
},
explosionGenerator = [[custom:flash2purple]],
fireStarter = 30,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 4.33,
minIntensity = 1,
noSelfDamage = true,
range = 350,
reloadtime = 2,
rgbColor = [[0.3 0 0.4]],
soundStart = [[weapon/laser/heavy_laser5]],
soundStartVolume = 3,
soundTrigger = true,
sweepfire = false,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 8,
tolerance = 18000,
turret = false,
weaponType = [[BeamLaser]],
weaponVelocity = 500,
},
},
}
return lowerkeys({ droneheavyslow = unitDef })
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/hound.lua | 1 | 8976 | require "brains/houndbrain"
require "stategraphs/SGhound"
local trace = function() end
local assets=
{
Asset("ANIM", "anim/hound_basic.zip"),
Asset("ANIM", "anim/hound.zip"),
Asset("ANIM", "anim/hound_red.zip"),
Asset("ANIM", "anim/hound_ice.zip"),
Asset("SOUND", "sound/hound.fsb"),
}
local prefabs =
{
"houndstooth",
"monstermeat",
"redgem",
"bluegem",
}
SetSharedLootTable( 'hound',
{
{'monstermeat', 1.000},
{'houndstooth', 0.125},
})
SetSharedLootTable( 'hound_fire',
{
{'monstermeat', 1.0},
{'houndstooth', 1.0},
{'houndfire', 1.0},
{'houndfire', 1.0},
{'houndfire', 1.0},
{'redgem', 0.2},
})
SetSharedLootTable( 'hound_cold',
{
{'monstermeat', 1.0},
{'houndstooth', 1.0},
{'houndstooth', 1.0},
{'bluegem', 0.2},
})
local WAKE_TO_FOLLOW_DISTANCE = 8
local SLEEP_NEAR_HOME_DISTANCE = 10
local SHARE_TARGET_DIST = 30
local HOME_TELEPORT_DIST = 30
local function ShouldWakeUp(inst)
return DefaultWakeTest(inst) or (inst.components.follower and inst.components.follower.leader and not inst.components.follower:IsNearLeader(WAKE_TO_FOLLOW_DISTANCE))
end
local function ShouldSleep(inst)
return inst:HasTag("pet_hound")
and not GetClock():IsDay()
and not (inst.components.combat and inst.components.combat.target)
and not (inst.components.burnable and inst.components.burnable:IsBurning() )
and (not inst.components.homeseeker or inst:IsNear(inst.components.homeseeker.home, SLEEP_NEAR_HOME_DISTANCE))
end
local function OnNewTarget(inst, data)
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
local function retargetfn(inst)
local dist = TUNING.HOUND_TARGET_DIST
if inst:HasTag("pet_hound") then
dist = TUNING.HOUND_FOLLOWER_TARGET_DIST
end
return FindEntity(inst, dist, function(guy)
return not guy:HasTag("wall") and not guy:HasTag("houndmound") and not (guy:HasTag("hound") or guy:HasTag("houndfriend")) and inst.components.combat:CanTarget(guy)
end)
end
local function KeepTarget(inst, target)
return inst.components.combat:CanTarget(target) and (not inst:HasTag("pet_hound") or inst:IsNear(target, TUNING.HOUND_FOLLOWER_TARGET_KEEP))
end
local function OnAttacked(inst, data)
inst.components.combat:SetTarget(data.attacker)
inst.components.combat:ShareTarget(data.attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("hound") or dude:HasTag("houndfriend") and not dude.components.health:IsDead() end, 5)
end
local function OnAttackOther(inst, data)
inst.components.combat:ShareTarget(data.target, SHARE_TARGET_DIST, function(dude) return dude:HasTag("hound") or dude:HasTag("houndfriend") and not dude.components.health:IsDead() end, 5)
end
local function GetReturnPos(inst)
local rad = 2
local pos = inst:GetPosition()
trace("GetReturnPos", inst, pos)
local angle = math.random()*2*PI
pos = pos + Point(rad*math.cos(angle), 0, -rad*math.sin(angle))
trace(" ", pos)
return pos:Get()
end
local function DoReturn(inst)
--print("DoReturn", inst)
if inst.components.homeseeker and inst.components.homeseeker:HasHome() then
if inst:HasTag("pet_hound") then
if inst.components.homeseeker.home:IsAsleep() and not inst:IsNear(inst.components.homeseeker.home, HOME_TELEPORT_DIST) then
local x, y, z = GetReturnPos(inst.components.homeseeker.home)
inst.Physics:Teleport(x, y, z)
trace("hound warped home", x, y, z)
end
elseif inst.components.homeseeker.home.components.childspawner then
inst.components.homeseeker.home.components.childspawner:GoHome(inst)
end
end
end
local function OnNight(inst)
--print("OnNight", inst)
if inst:IsAsleep() then
DoReturn(inst)
end
end
local function OnEntitySleep(inst)
--print("OnEntitySleep", inst)
if not GetClock():IsDay() then
DoReturn(inst)
end
end
local function OnSave(inst, data)
data.ispet = inst:HasTag("pet_hound")
--print("OnSave", inst, data.ispet)
end
local function OnLoad(inst, data)
--print("OnLoad", inst, data.ispet)
if data and data.ispet then
inst:AddTag("pet_hound")
inst:AddComponent("follower")
if inst.sg then
inst.sg:GoToState("idle")
end
end
end
local function fncommon()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local physics = inst.entity:AddPhysics()
local sound = inst.entity:AddSoundEmitter()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 2.5, 1.5 )
inst.Transform:SetFourFaced()
inst:AddTag("scarytoprey")
inst:AddTag("monster")
inst:AddTag("hostile")
inst:AddTag("hound")
MakeCharacterPhysics(inst, 10, .5)
anim:SetBank("hound")
anim:SetBuild("hound")
anim:PlayAnimation("idle")
inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
inst.components.locomotor.runspeed = TUNING.HOUND_SPEED
inst:SetStateGraph("SGhound")
local brain = require "brains/houndbrain"
inst:SetBrain(brain)
inst:AddComponent("eater")
inst.components.eater:SetCarnivore()
inst.components.eater:SetCanEatHorrible()
inst.components.eater.strongstomach = true -- can eat monster meat!
inst:AddComponent("health")
inst.components.health:SetMaxHealth(TUNING.HOUND_HEALTH)
inst:AddComponent("sanityaura")
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
inst:AddComponent("combat")
inst.components.combat:SetDefaultDamage(TUNING.HOUND_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.HOUND_ATTACK_PERIOD)
inst.components.combat:SetRetargetFunction(3, retargetfn)
inst.components.combat:SetKeepTargetFunction(KeepTarget)
inst.components.combat:SetHurtSound("dontstarve/creatures/hound/hurt")
inst:AddComponent("lootdropper")
inst.components.lootdropper:SetChanceLootTable('hound')
inst:AddComponent("inspectable")
inst:AddComponent("sleeper")
inst.components.sleeper:SetResistance(3)
inst.components.sleeper.testperiod = GetRandomWithVariance(6, 2)
inst.components.sleeper:SetSleepTest(ShouldSleep)
inst.components.sleeper:SetWakeTest(ShouldWakeUp)
inst:ListenForEvent("newcombattarget", OnNewTarget)
inst:ListenForEvent( "dusktime", function() OnNight( inst ) end, GetWorld())
inst:ListenForEvent( "nighttime", function() OnNight( inst ) end, GetWorld())
inst.OnEntitySleep = OnEntitySleep
inst.OnSave = OnSave
inst.OnLoad = OnLoad
inst:ListenForEvent("attacked", OnAttacked)
inst:ListenForEvent("onattackother", OnAttackOther)
return inst
end
local function fndefault()
local inst = fncommon(Sim)
MakeMediumFreezableCharacter(inst, "hound_body")
MakeMediumBurnableCharacter(inst, "hound_body")
return inst
end
local function fnfire(Sim)
local inst = fncommon(Sim)
inst.AnimState:SetBuild("hound_red")
MakeMediumFreezableCharacter(inst, "hound_body")
inst.components.freezable:SetResistance(4) --because fire
inst.components.combat:SetDefaultDamage(TUNING.FIREHOUND_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.FIREHOUND_ATTACK_PERIOD)
inst.components.locomotor.runspeed = TUNING.FIREHOUND_SPEED
inst.components.health:SetMaxHealth(TUNING.FIREHOUND_HEALTH)
inst.components.lootdropper:SetChanceLootTable('hound_fire')
inst:ListenForEvent("death", function(inst)
inst.SoundEmitter:PlaySound("dontstarve/creatures/hound/firehound_explo", "explosion")
end)
return inst
end
local function fncold(Sim)
local inst = fncommon(Sim)
inst.AnimState:SetBuild("hound_ice")
MakeMediumBurnableCharacter(inst, "hound_body")
inst.components.combat:SetDefaultDamage(TUNING.ICEHOUND_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.ICEHOUND_ATTACK_PERIOD)
inst.components.locomotor.runspeed = TUNING.ICEHOUND_SPEED
inst.components.health:SetMaxHealth(TUNING.ICEHOUND_HEALTH)
inst.components.lootdropper:SetChanceLootTable('hound_cold')
inst:ListenForEvent("death", function(inst)
inst.SoundEmitter:PlaySound("dontstarve/creatures/hound/icehound_explo", "explosion")
end)
return inst
end
local function fnfiredrop(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
MakeInventoryPhysics(inst)
MakeLargeBurnable(inst, 6+ math.random()*6)
MakeLargePropagator(inst)
inst.components.burnable:Ignite()
inst.persists = false
inst.components.burnable:SetOnExtinguishFn(function(inst) inst:Remove() end)
return inst
end
return Prefab( "monsters/hound", fndefault, assets, prefabs),
Prefab( "monsters/firehound", fnfire, assets, prefabs),
Prefab( "monsters/icehound", fncold, assets, prefabs),
Prefab( "monsters/houndfire", fnfiredrop, assets, prefabs)
| gpl-2.0 |
AllAboutEE/nodemcu-firmware | lua_modules/ds3231/ds3231-web.lua | 84 | 1338 | require('ds3231')
port = 80
-- ESP-01 GPIO Mapping
gpio0, gpio2 = 3, 4
days = {
[1] = "Sunday",
[2] = "Monday",
[3] = "Tuesday",
[4] = "Wednesday",
[5] = "Thursday",
[6] = "Friday",
[7] = "Saturday"
}
months = {
[1] = "January",
[2] = "Febuary",
[3] = "March",
[4] = "April",
[5] = "May",
[6] = "June",
[7] = "July",
[8] = "August",
[9] = "September",
[10] = "October",
[11] = "November",
[12] = "December"
}
ds3231.init(gpio0, gpio2)
srv=net.createServer(net.TCP)
srv:listen(port,
function(conn)
second, minute, hour, day, date, month, year = ds3231.getTime()
prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second)
conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<!DOCTYPE HTML>" ..
"<html><body>" ..
"<b>ESP8266</b></br>" ..
"Time and Date: " .. prettyTime .. "<br>" ..
"Node ChipID : " .. node.chipid() .. "<br>" ..
"Node MAC : " .. wifi.sta.getmac() .. "<br>" ..
"Node Heap : " .. node.heap() .. "<br>" ..
"Timer Ticks : " .. tmr.now() .. "<br>" ..
"</html></body>")
conn:on("sent",function(conn) conn:close() end)
end
) | mit |
willthames/photodeck.lrdevplugin | PhotoDeckAPIXSLT.lua | 1 | 7029 | local LrXml = import 'LrXml'
local logger = import 'LrLogger'( 'PhotoDeckPublishLightroomPlugin' )
logger:enable('logfile')
local xsltheader = [====[
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/reply/*"/>
]====]
local xsltfooter = [====[
</xsl:stylesheet>
]====]
local PhotoDeckAPIXSLT = {}
PhotoDeckAPIXSLT.error = xsltheader .. [=====[
<xsl:template match='/reply'>
return "<xsl:value-of select='error'/>"
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.ping = xsltheader .. [=====[
<xsl:template match='/reply'>
return [====[<xsl:value-of select='message'/>]====]
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.user = xsltheader .. [=====[
<xsl:template match='/reply/user'>
local t = {
firstname = [====[<xsl:value-of select='firstname'/>]====],
lastname = [====[<xsl:value-of select='lastname'/>]====],
email = "<xsl:value-of select='email'/>",
}
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.websites = xsltheader .. [=====[
<xsl:template match='/reply/websites'>
local t = {}
<xsl:for-each select='website'>
t["<xsl:value-of select='urlname'/>"] = {
hostname = "<xsl:value-of select='hostname'/>",
homeurl = "<xsl:value-of select='home-url'/>",
title = [====[<xsl:value-of select='title'/>]====],
uuid = "<xsl:value-of select='uuid'/>",
rootgalleryuuid = "<xsl:value-of select='root-gallery-uuid'/>",
}
</xsl:for-each>
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.galleries = xsltheader .. [=====[
<xsl:template match='/reply/galleries'>
LrDate = import 'LrDate'
local PhotoDeckUtils = require 'PhotoDeckUtils'
local t = {}
<xsl:for-each select='gallery'>
t["<xsl:value-of select='uuid'/>"] = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = [====[<xsl:value-of select='name'/>]====],
uuid = "<xsl:value-of select='uuid'/>",
description = [====[<xsl:value-of select='description'/>]====],
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
publishedat = PhotoDeckUtils.XMLDateTimeToCoca("<xsl:value-of select='published-at'/>"),
mediascount = "<xsl:value-of select='medias-count'/>",
displaystyle = "<xsl:value-of select='gallery-display-style-uuid'/>",
}
</xsl:for-each>
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.gallery = xsltheader .. [=====[
<xsl:template match='/reply/gallery'>
LrDate = import 'LrDate'
local PhotoDeckUtils = require 'PhotoDeckUtils'
local t = {
fullurlpath = "<xsl:value-of select='full-url-path'/>",
name = [====[<xsl:value-of select='name'/>]====],
uuid = "<xsl:value-of select='uuid'/>",
description = [====[<xsl:value-of select='description'/>]====],
urlpath = "<xsl:value-of select='url-path'/>",
parentuuid = "<xsl:value-of select='parent-uuid'/>",
publishedat = PhotoDeckUtils.XMLDateTimeToCoca("<xsl:value-of select='published-at'/>"),
displaystyle = "<xsl:value-of select='gallery-display-style-uuid'/>",
}
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.media = xsltheader .. [=====[
<xsl:template match='/reply/media'>
local t = {
uuid = "<xsl:value-of select='uuid'/>",
<xsl:if test="file-name">
filename = [====[<xsl:value-of select='file-name'/>]====],
</xsl:if>
<xsl:if test="title">
title = [====[<xsl:value-of select='title'/>]====],
</xsl:if>
<xsl:if test="file-name">
description = [====[<xsl:value-of select='description'/>]====],
</xsl:if>
<xsl:if test="keywords">
<xsl:apply-templates select='keywords'/>
</xsl:if>
<xsl:if test="galleries">
<xsl:apply-templates select='galleries'/>
</xsl:if>
}
<xsl:if test="upload-location">
t.uploadlocation = "<xsl:value-of select='upload-location'/>"
</xsl:if>
<xsl:if test="upload-url">
t.uploadurl = "<xsl:value-of select='upload-url'/>"
</xsl:if>
<xsl:if test="upload-method">
t.uploadmethod = "<xsl:value-of select='upload-method'/>"
</xsl:if>
<xsl:if test="upload-file-param">
t.uploadfileparam = "<xsl:value-of select='upload-file-param'/>"
</xsl:if>
<xsl:if test="upload-params">
t.uploadparams = {}
<xsl:for-each select='upload-params/*'>
t.uploadparams["<xsl:value-of select='name()'/>"] = [====[<xsl:value-of select='.'/>]====]
</xsl:for-each>
</xsl:if>
return t
</xsl:template>
<xsl:template match='galleries'>
galleries = {
<xsl:for-each select='gallery'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
},
</xsl:template>
<xsl:template match='keywords'>
keywords = {
<xsl:for-each select='keyword'>
[====[<xsl:value-of select='.'/>]====],
</xsl:for-each>
},
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.mediasInGallery = xsltheader .. [=====[
<xsl:template match='/reply/gallery/*'/>
<xsl:template match='/reply/gallery/medias'>
local t = {
<xsl:for-each select='media'>
"<xsl:value-of select='uuid'/>",
</xsl:for-each>
}
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.subGalleriesInGallery = xsltheader .. [=====[
<xsl:template match='/reply/galleries'>
local t = {}
<xsl:for-each select='gallery'>
t["<xsl:value-of select='uuid'/>"] = {
name = [====[<xsl:value-of select='name'/>]====],
parentuuid = "<xsl:value-of select='parent-uuid'/>",
subgalleriescount = "<xsl:value-of select='subgalleries-count'/>",
page = "<xsl:value-of select='page'/>",
totalpages = "<xsl:value-of select='total-pages'/>"
}
</xsl:for-each>
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.totalPages = xsltheader .. [=====[
<xsl:template match='/reply'>
return "<xsl:value-of select='total-pages'/>"
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.uploadStopWithError = xsltheader .. [=====[
<xsl:template match='/reply'>
return "<xsl:value-of select='stop-with-error'/>"
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.galleryDisplayStyles = xsltheader .. [=====[
<xsl:template match='/reply/gallery-display-styles'>
local t = {}
<xsl:for-each select='gallery-display-style'>
t["<xsl:value-of select='uuid'/>"] = {
uuid = "<xsl:value-of select='uuid'/>",
name = [====[<xsl:value-of select='name'/>]====],
}
</xsl:for-each>
return t
</xsl:template>
]=====] .. xsltfooter
PhotoDeckAPIXSLT.transform = function(xmlstring, xslt)
if xmlstring and string.sub(xmlstring, 1, 5) == '<?xml' then
-- prevent LUA code injection
local _
xmlstring, _ = string.gsub(xmlstring, '%[====%[', '')
xmlstring, _ = string.gsub(xmlstring, '%]====%]', '')
-- parse & load
--logger:trace("XML: " .. xmlstring)
local xml = LrXml.parseXml(xmlstring)
local luastring = xml:transform(xslt)
--logger:trace("LUA: " .. luastring)
if luastring ~= '' then
local f = assert(loadstring(luastring))
return f()
else
logger:trace(xmlstring)
end
end
end
return PhotoDeckAPIXSLT
| mit |
czfshine/Don-t-Starve | mods/Cretaceous/wicker/kernel_extensions/dst_abstraction/componentactions.lua | 6 | 9531 | --[[
-- IMPORTANT:
-- The modinfo.id is being hacked in place of 'modname' for identification.
--]]
local Lambda = wickerrequire "paradigms.functional"
if IsWorldgen() then
init = Lambda.Nil
return _M
end
local Rest = pkgrequire "restriction"
---
if IsDST() then
require "entityscript"
local SHOULD_FAKE_SERVER_MODNAMES = false
_G.ModManager.GetServerModsNames = (function()
local GetServerModsNames = assert( _G.ModManager.GetServerModsNames )
local modname = assert( modenv.modname )
local id = assert( modinfo.id )
local function modname_mapper(name)
if name == modname then
return id
else
return name
end
end
return function(self, ...)
local modlist = GetServerModsNames(self, ...)
if SHOULD_FAKE_SERVER_MODNAMES then
return Lambda.CompactlyMap(modname_mapper, ipairs(modlist))
else
return modlist
end
end
end)()
_G.Entity.AddNetwork = (function()
local AddNetwork = _G.Entity.AddNetwork
return function(self)
SHOULD_FAKE_SERVER_MODNAMES = true
local ret = AddNetwork(self)
SHOULD_FAKE_SERVER_MODNAMES = false
return ret
end
end)()
end
---
-- Maps DST's action type IDs to DS's component method names.
local actiontype_map = {
EQUIPPED = "CollectEquippedActions",
INVENTORY = "CollectInventoryActions",
POINT = "CollectPointActions",
SCENE = "CollectSceneActions",
USEITEM = "CollectUseActions",
ISVALID = "IsActionValid",
}
local function ActionTypeToMethodName(actiontype)
local name = actiontype_map[actiontype]
if name == nil then
return error("Invalid action type '"..tostring(actiontype).."'.", 2)
end
return name
end
local GetComponentActions
if IsDST() then
GetComponentActions = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return assert(Reflection.RequireUpvalue(_G.EntityScript.CollectActions, "COMPONENT_ACTIONS"))
end)
else
GetComponentActions = Rest.ForbiddenFunction("GetComponentActions", "singleplayer")
end
local GetModComponentActions
if IsDST() then
GetModComponentActions = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return assert(Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_COMPONENT_ACTIONS"))
end)
else
GetModComponentActions = Rest.ForbiddenFunction("GetModComponentActions", "singleplayer")
end
local GetActionComponentIDs
if IsDST() then
GetActionComponentIDs = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.EntityScript.RegisterComponentActions, "ACTION_COMPONENT_IDS")
end)
else
GetActionComponentIDs = Rest.ForbiddenFunction("GetActionComponentIDs", "singleplayer")
end
local GetModActionComponentIDs
if IsDST() then
GetModActionComponentIDs = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_ACTION_COMPONENT_IDS")
end)
else
GetModActionComponentIDs = Rest.ForbiddenFunction("GetModActionComponentIDs", "singleplayer")
end
local GetActionComponentNames
if IsDST() then
GetActionComponentNames = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.EntityScript.CollectActions, "ACTION_COMPONENT_NAMES")
end)
else
GetActionComponentNames = Rest.ForbiddenFunction("GetActionComponentNames", "singleplayer")
end
local GetModActionComponentNames
if IsDST() then
GetModActionComponentNames = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_ACTION_COMPONENT_NAMES")
end)
else
GetModActionComponentNames = Rest.ForbiddenFunction("GetModActionComponentNames", "singleplayer")
end
---
local AddComponentAction, PatchComponentAction
if IsDST() then
assert(modenv.AddComponentAction)
assert(TheMod.AddComponentAction)
AddComponentAction = function(actiontype, cmp_name, fn)
return _G.AddComponentAction(actiontype, cmp_name, fn, modinfo.id)
end
PatchComponentAction = function(actiontype, cmp_name, patcher)
local cas = GetComponentActions()
local subcas = cas[actiontype]
if not subcas then
return AddComponentAction(actiontype, cmp_name, patcher(nil, actiontype, cmp_name))
end
local fn = subcas[cmp_name]
subcas[cmp_name] = patcher(fn, actiontype, cmp_name)
end
else
local function wrapComponentActionFn(fn)
return function(self, ...)
return fn(self.inst, ...)
end
end
local function unwrapComponentActionFn(fn, cmp_name)
return function(inst, ...)
local cmp = inst.components[cmp_name]
if cmp then
return fn(cmp, ...)
end
end
end
AddComponentAction = function(actiontype, cmp_name, fn)
local cmp = require("components/"..cmp_name)
local method_name = actiontype_map[actiontype]
if method_name == nil then
return error("Attempt to add component action of invalid action type '"..tostring(actiontype).."' to component '"..cmp_name, 2)
end
cmp[method_name] = wrapComponentActionFn(fn)
end
PatchComponentAction = function(actiontype, cmp_name, patcher)
local cmp = require("components/"..cmp_name)
local method_name = actiontype_map[actiontype]
if method_name then
local fn = cmp[method_name]
if fn then
fn = unwrapComponentActionFn(fn, cmp_name)
end
cmp[method_name] = wrapComponentActionFn( patcher(fn, actiontype, cmp_name) )
end
end
end
TheMod:EmbedAdder("ComponentAction", AddComponentAction)
function TheMod:PatchComponentAction(...)
return PatchComponentAction(...)
end
-- Takes a table in the same format as COMPONENT_ACTIONS found in DST's componentactions.lua.
local function AddComponentsActions(data)
for actiontype, subdata in pairs(data) do
for cmp_name, fn in pairs(subdata) do
AddComponentAction(actiontype, cmp_name, fn)
end
end
end
TheMod:EmbedAdder("ComponentsActions", AddComponentsActions)
---
local HasActionComponent
if IsDST() then
local set_key = {}
local dirty_set_key = {}
---
local function genericUpdateActionComponentSet(set, id_list, id_map, value)
local current_ids = {}
for _, id in ipairs(id_list) do
current_ids[id] = true
end
for k, v in pairs(set) do
if v == value and not current_ids[id_map[k]] then
set[k] = nil
end
end
for id, k in pairs(id_map) do
if current_ids[id] and set[k] == nil then
set[k] = value
end
end
end
---
local function updateActionComponentSet(inst)
local set = assert( inst[set_key] )
local id_map = GetActionComponentIDs()
return genericUpdateActionComponentSet(set, inst.actioncomponents, id_map, true)
end
local function updateModActionComponentSet(inst, mod_name)
assert( mod_name )
local set = assert( inst[set_key] )
local id_list = inst.modactioncomponents[mod_name]
if id_list == nil then return end
local id_map = GetModActionComponentIDs()[mod_name]
if id_map == nil then return end
return genericUpdateActionComponentSet(set, id_list, id_map, mod_name)
end
local function cleanDirtySets(inst)
local set = inst[dirty_set_key]
if set == nil then return end
for k in pairs(set) do
if k == 1 then
updateActionComponentSet(inst)
else
updateModActionComponentSet(inst, k)
end
end
inst[dirty_set_key] = nil
end
local function flagDirtyActionComponentSet(inst)
local set = inst[dirty_set_key]
if set == nil then
set = {nil}
inst[dirty_set_key] = set
end
set[1] = true
end
local getDirtyModActionComponentSetFlagger = (function()
local cache = {}
return function(mod_name)
local ret = cache[mod_name]
if ret == nil then
ret = function(inst)
local set = inst[dirty_set_key]
if set == nil then
set = {_ = nil}
inst[dirty_set_key] = set
end
set[mod_name] = true
end
cache[mod_name] = ret
end
return ret
end
end)()
local function initializeActionComponentSet(inst)
if inst.actionreplica then
inst:ListenForEvent("actioncomponentsdirty", flagDirtyActionComponentSet)
for modname in pairs(inst.actionreplica.modactioncomponents) do
inst:ListenForEvent("modactioncomponentsdirty"..modname, getDirtyModActionComponentSetFlagger(modname))
end
end
updateActionComponentSet(inst)
if inst.modactioncomponents then
for modname in pairs(inst.modactioncomponents) do
updateModActionComponentSet(inst, modname)
end
end
end
HasActionComponent = function(inst, cmp_name)
local set = inst[set_key]
if set == nil then
set = {}
inst[set_key] = set
initializeActionComponentSet(inst)
else
cleanDirtySets(inst)
end
return set[cmp_name] and true or false
end
else
HasActionComponent = function(inst, cmp_name)
return inst.components[cmp_name] ~= nil
end
end
---
function init(kernel)
kernel.GetComponentActions = GetComponentActions
kernel.GetModComponentActions = GetModComponentActions
kernel.GetActionComponentIDs = GetActionComponentIDs
kernel.GetModActionComponentIDs = GetModActionComponentIDs
kernel.GetActionComponentNames = GetActionComponentNames
kernel.GetModActionComponentNames = GetModActionComponentNames
kernel.ActionTypeToMethodName = ActionTypeToMethodName
kernel.HasActionComponent = HasActionComponent
end
| gpl-2.0 |
CrazyEddieTK/Zero-K | units/dynassault1.lua | 5 | 2658 | unitDef = {
unitname = [[dynassault1]],
name = [[Guardian Commander]],
description = [[Heavy Combat Commander]],
acceleration = 0.18,
activateWhenBuilt = true,
brakeRate = 0.375,
buildCostMetal = 1200,
buildDistance = 144,
builder = true,
buildoptions = {
},
buildPic = [[benzcom.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[45 54 45]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
level = [[1]],
statsname = [[dynassault1]],
soundok = [[heavy_bot_move]],
soundselect = [[bot_select]],
soundbuild = [[builder_start]],
commtype = [[5]],
modelradius = [[27]],
dynamic_comm = 1,
},
energyStorage = 500,
energyUse = 0,
explodeAs = [[ESTOR_BUILDINGEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[commander1]],
idleAutoHeal = 5,
idleTime = 0,
leaveTracks = true,
losEmitHeight = 40,
maxDamage = 3600,
maxSlope = 36,
maxVelocity = 1.35,
maxWaterDepth = 5000,
metalStorage = 500,
minCloakDistance = 75,
movementClass = [[AKBOT2]],
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK]],
objectName = [[benzcom1.s3o]],
script = [[dynassault.lua]],
selfDestructAs = [[ESTOR_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:RAIDMUZZLE]],
[[custom:LEVLRMUZZLE]],
[[custom:RAIDMUZZLE]],
[[custom:NONE]],
[[custom:NONE]],
[[custom:NONE]],
},
},
showNanoSpray = false,
sightDistance = 500,
sonarDistance = 500,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 1148,
upright = true,
workerTime = 10,
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[benzcom1_wreck.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ dynassault1 = unitDef })
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Gadgets/game_over.lua | 3 | 21832 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Game Over",
desc = "GAME OVER!! (handles conditions thereof)",
author = "SirMaverick, Google Frog, KDR_11k, CarRepairer (unified by KingRaptor)",
date = "2009",
license = "GPL",
layer = 1,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
-- End game if only one allyteam with players AND units is left.
-- An allyteam is counted as dead if none of
-- its active players have units left.
--------------------------------------------------------------------------------
local isScriptMission = VFS.FileExists("mission.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetTeamInfo = Spring.GetTeamInfo
local spGetTeamList = Spring.GetTeamList
local spGetTeamUnits = Spring.GetTeamUnits
local spDestroyUnit = Spring.DestroyUnit
local spGetAllUnits = Spring.GetAllUnits
local spGetAllyTeamList = Spring.GetAllyTeamList
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetPlayerList = Spring.GetPlayerList
local spAreTeamsAllied = Spring.AreTeamsAllied
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetUnitHealth = Spring.GetUnitHealth
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spTransferUnit = Spring.TransferUnit
local spGetGameRulesParam = Spring.GetGameRulesParam
local spKillTeam = Spring.KillTeam
local spGameOver = Spring.GameOver
local spEcho = Spring.Echo
local COMM_VALUE = UnitDefNames.armcom1.metalCost or 1200
local ECON_SUPREMACY_MULT = 25
local MISSION_PLAYER_ALLY_TEAM_ID = 0
local SPARE_PLANETWARS_UNITS = false
local SPARE_REGULAR_UNITS = false
--------------------------------------------------------------------------------
-- vars
--------------------------------------------------------------------------------
local gaiaTeamID = Spring.GetGaiaTeamID()
local gaiaAllyTeamID = select(6, Spring.GetTeamInfo(gaiaTeamID))
local chickenAllyTeamID
local aliveCount = {}
local aliveValue = {}
local destroyedAlliances = {}
local allianceToReveal
local finishedUnits = {} -- this stores a list of all units that have ever been completed, so it can distinguish between incomplete and partly reclaimed units
local toDestroy = {}
local alliancesToDestroy
local modOptions = Spring.GetModOptions() or {}
local commends = tobool(modOptions.commends)
local noElo = tobool(modOptions.noelo)
local campaignBattleID = Spring.GetModOptions().singleplayercampaignbattleid and true
local revealed = false
local gameover = false
local gameOverSent = false
local inactiveWinAllyTeam = false
local nilUnitDef = {id=-1}
local function GetUnitDefIdByName(defName)
return (UnitDefNames[defName] or nilUnitDef).id
end
local doesNotCountList
if campaignBattleID then
doesNotCountList = {
[GetUnitDefIdByName("terraunit")] = true,
}
else
doesNotCountList = {
[GetUnitDefIdByName("spiderscout")] = true,
[GetUnitDefIdByName("shieldbomb")] = true,
[GetUnitDefIdByName("cloakbomb")] = true,
[GetUnitDefIdByName("amphbomb")] = true,
[GetUnitDefIdByName("gunshipbomb")] = true,
[GetUnitDefIdByName("terraunit")] = true,
}
-- auto detection of doesnotcount units
for name, ud in pairs(UnitDefs) do
if (ud.customParams.dontcount) then
doesNotCountList[ud.id] = true
elseif (ud.isFeature) then
doesNotCountList[ud.id] = true
elseif (not ud.canAttack) and (not ud.speed) and (not ud.isFactory) then
doesNotCountList[ud.id] = true
end
end
end
local commsAlive = {}
local allyTeams = spGetAllyTeamList()
for i = 1, #allyTeams do
commsAlive[allyTeams[i]] = {}
end
local aiTeamResign = not (isScriptMission or campaignBattleID or (Spring.GetModOptions().disableAiTeamResign == 1))
local vitalConstructorAllyTeam = {}
local vitalAlive = {}
local allyTeams = spGetAllyTeamList()
for i = 1, #allyTeams do
local allyTeamID = allyTeams[i]
vitalAlive[allyTeamID] = {}
if aiTeamResign then
local teamList = Spring.GetTeamList(allyTeamID)
vitalConstructorAllyTeam[allyTeamID] = true
for j = 1, #teamList do
local isAiTeam = select(4, Spring.GetTeamInfo(teamList[j]))
if not isAiTeam then
vitalConstructorAllyTeam[allyTeamID] = false
break
end
end
end
end
--------------------------------------------------------------------------------
-- Mission handling
--------------------------------------------------------------------------------
local isMission = (Spring.GetModOptions().singleplayercampaignbattleid and true) or false
local PLAYER_ALLY_TEAM_ID = 0
local PLAYER_TEAM_ID = 0
local function KillTeam(teamID)
if isMission then
if teamID == PLAYER_TEAM_ID then
GG.MissionGameOver(false)
end
else
spKillTeam(teamID)
end
end
local function GameOver(winningAllyTeamID)
if isMission then
if winningAllyTeamID == PLAYER_ALLY_TEAM_ID then
GG.MissionGameOver(true)
end
else
spGameOver({winningAllyTeamID})
end
end
function GG.IsAllyTeamAlive(allyTeamID)
return not destroyedAlliances[allyTeamID]
end
--------------------------------------------------------------------------------
-- local funcs
--------------------------------------------------------------------------------
local function GetTeamIsChicken(teamID)
local luaAI = Spring.GetTeamLuaAI(teamID)
if luaAI and string.find(string.lower(luaAI), "chicken") then
return true
end
return false
end
local function CountAllianceUnits(allianceID)
local teamlist = spGetTeamList(allianceID) or {}
local count = 0
for i=1,#teamlist do
local teamID = teamlist[i]
count = count + (aliveCount[teamID] or 0)
if (GG.waitingForComm or {})[teamID] then
count = count + 1
end
end
return count
end
local function CountAllianceValue(allianceID)
local teamlist = spGetTeamList(allianceID) or {}
local value = 0
for i=1,#teamlist do
local teamID = teamlist[i]
value = value + (aliveValue[teamID] or 0)
if (GG.waitingForComm or {})[teamID] then
value = value + COMM_VALUE
end
end
return value
end
local function HasNoComms(allianceID)
for unitID in pairs(commsAlive[allianceID]) do
return false
end
return true
end
local function HasNoVitalUnits(allianceID)
for unitID in pairs(vitalAlive[allianceID]) do
return false
end
return true
end
local function EchoUIMessage(message)
spEcho("game_message: " .. message)
end
local function UnitWithinBounds(unitID)
local x, y, z = Spring.GetUnitPosition(unitID)
return (x > -500) and (x < Game.mapSizeX + 500) and (y > -1000) and (z > -500) and (z < Game.mapSizeZ + 500)
end
local function Draw() -- declares a draw
if gameOverSent then
return
end
EchoUIMessage("The game ended in a draw!")
GameOver(gaiaAllyTeamID) -- exit uses {} so use Gaia for draw to differentiate
gameOverSent = true
end
-- if only one allyteam left, declare it the victor
local function CheckForVictory()
if Spring.IsCheatingEnabled() or gameOverSent then
return
end
local allylist = spGetAllyTeamList()
local count = 0
local lastAllyTeam
for _,a in pairs(allylist) do
if not destroyedAlliances[a] and (a ~= gaiaAllyTeamID) then
--Spring.Echo("Alliance " .. a .. " remains in the running")
count = count + 1
lastAllyTeam = a
end
end
if count < 2 then
if ((not lastAllyTeam) or (count == 0)) then
Draw()
else
if not (isMission or isScriptMission) then
local name = Spring.GetGameRulesParam("allyteam_long_name_" .. lastAllyTeam)
EchoUIMessage(name .. " wins!")
end
GameOver(lastAllyTeam)
gameOverSent = true
end
end
end
local function RevealAllianceUnits(allianceID)
allianceToReveal = allianceID
local teamList = spGetTeamList(allianceID)
for i=1,#teamList do
local t = teamList[i]
local teamUnits = spGetTeamUnits(t)
for j=1,#teamUnits do
local unitID = teamUnits[j]
-- purge extra-map units
if not UnitWithinBounds(unitID) then
Spring.DestroyUnit(unitID)
else
Spring.SetUnitAlwaysVisible(unitID, true)
end
end
end
end
-- purge the alliance! for the horde!
local function DestroyAlliance(allianceID, delayLossToNextGameFrame)
if delayLossToNextGameFrame then
alliancesToDestroy = alliancesToDestroy or {}
alliancesToDestroy[#alliancesToDestroy + 1] = allianceID
return
end
if not destroyedAlliances[allianceID] then
destroyedAlliances[allianceID] = true
local teamList = spGetTeamList(allianceID)
if teamList == nil or (#teamList == 0) then
return -- empty allyteam, don't bother
end
local explodeUnits = true
if GG.GalaxyCampaignHandler then
local defeatConfig = GG.GalaxyCampaignHandler.GetDefeatConfig(allianceID)
if defeatConfig then
if defeatConfig.allyTeamLossObjectiveID then
local objParameter = "objectiveSuccess_" .. defeatConfig.allyTeamLossObjectiveID
Spring.SetGameRulesParam(objParameter, (Spring.GetGameRulesParam(objParameter) or 0) + ((allianceID == MISSION_PLAYER_ALLY_TEAM_ID and 0) or 1))
end
if defeatConfig.defeatOtherAllyTeamsOnLoss then
local otherTeams = defeatConfig.defeatOtherAllyTeamsOnLoss
for i = 1, #otherTeams do
DestroyAlliance(otherTeams[i])
end
end
if defeatConfig.doNotExplodeOnLoss then
explodeUnits = false
end
end
end
if Spring.IsCheatingEnabled() then
EchoUIMessage("Game Over: DEBUG")
EchoUIMessage("Game Over: Allyteam " .. allianceID .. " has met the game over conditions.")
EchoUIMessage("Game Over: If this is true, then please resign.")
return -- don't perform victory check
else -- kaboom
if not (isMission or isScriptMission) then
local name = Spring.GetGameRulesParam("allyteam_long_name_" .. allianceID)
EchoUIMessage(name .. " has been destroyed!")
end
local frame = Spring.GetGameFrame() + 50
local function QueueDestruction(unitID)
local destroyFrame = frame - math.ceil((math.random()*7)^2)
toDestroy[destroyFrame] = toDestroy[destroyFrame] or {}
toDestroy[destroyFrame][unitID] = true
end
for i = 1, #teamList do
local t = teamList[i]
if explodeUnits then
local teamUnits = spGetTeamUnits(t)
for j = 1, #teamUnits do
local unitID = teamUnits[j]
local pwUnits = (GG.PlanetWars or {}).unitsByID
if pwUnits and pwUnits[unitID] then
if SPARE_PLANETWARS_UNITS then
GG.allowTransfer = true
spTransferUnit(unitID, gaiaTeamID, true) -- don't blow up PW buildings
GG.allowTransfer = false
else
QueueDestruction(unitID)
end
elseif not SPARE_REGULAR_UNITS then
QueueDestruction(unitID)
end
end
end
Spring.SetTeamRulesParam(t, "isDead", 1, {public = true})
KillTeam(t)
end
end
end
CheckForVictory()
end
GG.DestroyAlliance = DestroyAlliance
local function CauseVictory(allyTeamID)
local allylist = spGetAllyTeamList()
local count = 0
for _,a in pairs(allylist) do
if a ~= allyTeamID and a ~= gaiaAllyTeamID then
DestroyAlliance(a)
end
end
--GameOver(lastAllyTeam)
end
GG.CauseVictory = CauseVictory
local function CanAddCommander()
if not isScriptMission then
return true
end
local frame = Spring.GetGameFrame()
return frame < 10
end
local function AddAllianceUnit(unitID, unitDefID, teamID)
local _, _, _, _, _, allianceID = spGetTeamInfo(teamID)
aliveCount[teamID] = aliveCount[teamID] + 1
aliveValue[teamID] = aliveValue[teamID] + UnitDefs[unitDefID].metalCost
if CanAddCommander() and UnitDefs[unitDefID].customParams.commtype then
commsAlive[allianceID][unitID] = true
end
if GG.GalaxyCampaignHandler and GG.GalaxyCampaignHandler.VitalUnit(unitID) then
vitalAlive[allianceID][unitID] = true
elseif vitalConstructorAllyTeam[allianceID] then
local ud = UnitDefs[unitDefID]
if ud.isBuilder or ud.isFactory then
vitalAlive[allianceID][unitID] = true
end
end
end
local function CheckMissionDefeatOnUnitLoss(unitID, allianceID)
local defeatConfig = GG.GalaxyCampaignHandler.GetDefeatConfig(allianceID)
if defeatConfig.ignoreUnitLossDefeat then
return false
end
if defeatConfig.defeatIfUnitDestroyed and defeatConfig.defeatIfUnitDestroyed[unitID] then
if (not gameOverSent) and type(defeatConfig.defeatIfUnitDestroyed[unitID]) == "number" then
local objParameter = "objectiveSuccess_" .. defeatConfig.defeatIfUnitDestroyed[unitID]
local value = (allianceID == MISSION_PLAYER_ALLY_TEAM_ID and 0) or 1
Spring.SetGameRulesParam(objParameter, (Spring.GetGameRulesParam(objParameter) or 0) + value)
end
return true
end
if not (defeatConfig.vitalCommanders or defeatConfig.vitalUnitTypes) then
return (CountAllianceUnits(allianceID) <= 0) -- Default loss condition
end
if defeatConfig.vitalCommanders and not HasNoComms(allianceID) then
return false
end
if defeatConfig.vitalUnitTypes and not HasNoVitalUnits(allianceID) then
return false
end
return true
end
local function RemoveAllianceUnit(unitID, unitDefID, teamID, delayLossToNextGameFrame)
local _, _, _, _, _, allianceID = spGetTeamInfo(teamID)
aliveCount[teamID] = aliveCount[teamID] - 1
aliveValue[teamID] = aliveValue[teamID] - UnitDefs[unitDefID].metalCost
if aliveValue[teamID] < 0 then
aliveValue[teamID] = 0
end
if UnitDefs[unitDefID].customParams.commtype then
commsAlive[allianceID][unitID] = nil
end
if vitalAlive[allianceID] and vitalAlive[allianceID][unitID] then
vitalAlive[allianceID][unitID] = nil
end
if allianceID == chickenAllyTeamID then
return
end
if campaignBattleID then
if CheckMissionDefeatOnUnitLoss(unitID, allianceID) then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "<Game Over> Purging allyTeam " .. allianceID)
DestroyAlliance(allianceID, delayLossToNextGameFrame)
end
return
elseif vitalConstructorAllyTeam[allianceID] and HasNoVitalUnits(allianceID) then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "<Game Over> Purging allyTeam " .. allianceID)
DestroyAlliance(allianceID, delayLossToNextGameFrame)
end
if (CountAllianceUnits(allianceID) <= 0) or (commends and HasNoComms(allianceID)) then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "<Game Over> Purging allyTeam " .. allianceID)
DestroyAlliance(allianceID, delayLossToNextGameFrame)
end
end
local function CompareArmyValues(ally1, ally2)
local value1, value2 = CountAllianceValue(ally1), CountAllianceValue(ally2)
if value1 > ECON_SUPREMACY_MULT*value2 then
return ally1
elseif value2 > ECON_SUPREMACY_MULT*value1 then
return ally2
end
return nil
end
-- used during initialization
local function CheckAllUnits()
aliveCount = {}
local teams = spGetTeamList()
for i=1,#teams do
local teamID = teams[i]
if teamID ~= gaiaTeamID then
aliveCount[teamID] = 0
end
end
local units = spGetAllUnits()
for i=1,#units do
local unitID = units[i]
local teamID = spGetUnitTeam(unitID)
local unitDefID = spGetUnitDefID(unitID)
gadget:UnitFinished(unitID, unitDefID, teamID)
end
end
-- check for active players
local function ProcessLastAlly()
if Spring.IsCheatingEnabled() then
return
end
local allylist = spGetAllyTeamList()
local activeAllies = {}
local droppedAllies = {}
local lastActive = nil
for i = 1, #allylist do
repeat
local a = allylist[i]
if (a == gaiaAllyTeamID) then break end -- continue
if (destroyedAlliances[a]) then break end -- continue
local teamlist = spGetTeamList(a)
if (not teamlist) then break end -- continue
local hasActiveTeam = false
local hasDroppedTeam = false
for i=1,#teamlist do
local t = teamlist[i]
-- any team without units is dead to us; so only teams who are active AND have units matter
-- except chicken, who are alive even without units
local numAlive = aliveCount[t]
if #(Spring.GetTeamUnits(t)) == 0 then numAlive = 0 end
if (numAlive > 0) or (GG.waitingForComm or {})[t] or (GetTeamIsChicken(t)) then
-- count AI teams as active
local _,_,_,isAiTeam = spGetTeamInfo(t)
if isAiTeam then
hasActiveTeam = true
else
local playerlist = spGetPlayerList(t) -- active players
if playerlist then
for j = 1, #playerlist do
local name,active,spec = spGetPlayerInfo(playerlist[j])
if not spec then
if active then
hasActiveTeam = true
else
hasDroppedTeam = true
end
else
end
end
end
end
end
end
if hasActiveTeam then
activeAllies[#activeAllies+1] = a
lastActive = a
elseif hasDroppedTeam then
droppedAllies[#droppedAllies+1] = a
end
until true
end -- for
if #activeAllies > 1 and inactiveWinAllyTeam then
inactiveWinAllyTeam = false
Spring.SetGameRulesParam("inactivity_win", -1)
end
if #activeAllies == 2 then
if revealed or activeAllies[1] == chickenAllyTeamID or activeAllies[2] == chickenAllyTeamID then
return
end
-- run value comparison
local supreme = (not campaignBattleID) and CompareArmyValues(activeAllies[1], activeAllies[2])
if supreme then
EchoUIMessage("AllyTeam " .. supreme .. " has an overwhelming numerical advantage!")
for i=1, #allylist do
local a = allylist[i]
if (a ~= supreme) and (a ~= gaiaAllyTeamID) then
RevealAllianceUnits(a)
revealed = true
end
end
end
elseif #activeAllies < 2 then
if #droppedAllies > 0 then
if lastActive then
inactiveWinAllyTeam = lastActive
Spring.SetGameRulesParam("inactivity_win", lastActive)
else
Draw()
end
else
if #activeAllies == 1 then
-- remove every unit except for last active alliance
for i=1, #allylist do
local a = allylist[i]
if (a ~= lastActive) and (a ~= gaiaAllyTeamID) then
DestroyAlliance(a)
end
end
else -- no active team. For example two roaches were left and blew up each other
Draw()
end
end
end
end
local function CheckInactivityWin(cmd, line, words, player)
if inactiveWinAllyTeam and not gameover then
if player then
local name,_,spec,_,allyTeamID = Spring.GetPlayerInfo(player)
if allyTeamID == inactiveWinAllyTeam and not spec then
Spring.Echo((name or "") .. " has forced a win due to dropped opposition.")
CauseVictory(inactiveWinAllyTeam)
end
end
end
end
--------------------------------------------------------------------------------
-- callins
--------------------------------------------------------------------------------
function gadget:TeamDied (teamID)
if not gameover then
ProcessLastAlly()
end
end
-- supposed to solve game over not being called when resigning during pause
-- not actually called yet (PlayerChanged is unsynced at present)
function gadget:PlayerChanged (playerID)
if gameover then
return
end
ProcessLastAlly()
end
function gadget:UnitFinished(unitID, unitDefID, teamID)
if (teamID ~= gaiaTeamID)
and(not doesNotCountList[unitDefID])
and(not finishedUnits[unitID])
then
finishedUnits[unitID] = true
AddAllianceUnit(unitID, unitDefID, teamID)
end
end
function gadget:UnitCreated(unitID, unitDefID, teamID)
if revealed then
local allyTeam = select(6, spGetTeamInfo(teamID))
if allyTeam == allianceToReveal then
Spring.SetUnitAlwaysVisible(unitID, true)
end
end
end
function gadget:UnitDestroyed(unitID, unitDefID, teamID)
if spGetGameRulesParam("loadPurge") == 1 then
return
end
if (teamID ~= gaiaTeamID)
and(not doesNotCountList[unitDefID])
and finishedUnits[unitID]
then
finishedUnits[unitID] = nil
RemoveAllianceUnit(unitID, unitDefID, teamID)
end
end
-- note: Taken comes before Given
function gadget:UnitGiven(unitID, unitDefID, newTeam, oldTeamID)
if (newTeam ~= gaiaTeamID)
and (not doesNotCountList[unitDefID])
and finishedUnits[unitID]
then
AddAllianceUnit(unitID, unitDefID, newTeam)
end
end
function gadget:UnitTaken(unitID, unitDefID, oldTeamID, newTeam)
if (oldTeamID ~= gaiaTeamID)
and (not doesNotCountList[unitDefID])
and finishedUnits[unitID]
then
RemoveAllianceUnit(unitID, unitDefID, oldTeamID, true)
end
end
function gadget:Initialize()
local teams = spGetTeamList()
for i=1,#teams do
aliveValue[teams[i]] = 0
if GetTeamIsChicken(teams[i]) then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "<Game Over> Chicken team found")
chickenAllyTeamID = select(6, Spring.GetTeamInfo(teams[i]))
--break
end
end
CheckAllUnits()
gadgetHandler:AddChatAction('inactivitywin', CheckInactivityWin, "")
Spring.Log(gadget:GetInfo().name, LOG.INFO, "Game Over initialized")
end
function gadget:GameFrame(n)
if toDestroy[n] then
for unitID in pairs(toDestroy[n]) do
if Spring.ValidUnitID(unitID) then
local allyTeamID = Spring.GetUnitAllyTeam(unitID)
if destroyedAlliances[allyTeamID] then
spDestroyUnit(unitID, true)
end
end
end
toDestroy[n] = nil
end
if alliancesToDestroy then
for i = 1, #alliancesToDestroy do
DestroyAlliance(alliancesToDestroy[i])
end
alliancesToDestroy = nil
end
-- check for last ally:
-- end condition: only 1 ally with human players, no AIs in other ones
if (n % 45 == 0) then
if not gameover and not spGetGameRulesParam("loadedGame") then
ProcessLastAlly()
end
end
end
function gadget:GameOver()
gameover = true
if noElo then
Spring.SendCommands("wbynum 255 SPRINGIE:noElo")
end
Spring.Log(gadget:GetInfo().name, LOG.INFO, "GAME OVER!!")
end
| gpl-2.0 |
starkos/premake-core | modules/d/tests/test_ldc.lua | 7 | 2223 | ---
-- d/tests/test_dmd.lua
-- Automated test suite for dmd.
-- Copyright (c) 2011-2015 Manu Evans and the Premake project
---
local suite = test.declare("d_ldc")
local p = premake
local m = p.modules.d
local make = p.make
local project = p.project
---------------------------------------------------------------------------
-- Setup/Teardown
---------------------------------------------------------------------------
local wks, prj, cfg
function suite.setup()
p.escaper(make.esc)
wks = test.createWorkspace()
end
local function prepare_cfg(calls)
prj = p.workspace.getproject(wks, 1)
local cfg = test.getconfig(prj, "Debug")
local toolset = p.tools.ldc
p.callArray(calls, cfg, toolset)
end
--
-- Check configuration generation
--
function suite.dmd_dTools()
prepare_cfg({ m.make.dTools })
test.capture [[
DC = ldc2
]]
end
function suite.dmd_target()
prepare_cfg({ m.make.target })
test.capture [[
]]
end
function suite.dmd_target_separateCompilation()
compilationmodel "File"
prepare_cfg({ m.make.target })
test.capture [[
OUTPUTFLAG = -of="$@"
]]
end
function suite.dmd_versions()
versionlevel (10)
versionconstants { "A", "B" }
prepare_cfg({ m.make.versions })
test.capture [[
VERSIONS += -d-version=A -d-version=B -d-version=10
]]
end
function suite.dmd_debug()
debuglevel (10)
debugconstants { "A", "B" }
prepare_cfg({ m.make.debug })
test.capture [[
DEBUG += -d-debug=A -d-debug=B -d-debug=10
]]
end
function suite.dmd_imports()
importdirs { "dir1", "dir2/" }
prepare_cfg({ m.make.imports })
test.capture [[
IMPORTS += -I=dir1 -I=dir2
]]
end
function suite.dmd_dFlags()
prepare_cfg({ m.make.dFlags })
test.capture [[
ALL_DFLAGS += $(DFLAGS) -release $(VERSIONS) $(DEBUG) $(IMPORTS) $(STRINGIMPORTS) $(ARCH)
]]
end
function suite.dmd_linkCmd()
prepare_cfg({ m.make.linkCmd })
test.capture [[
BUILDCMD = $(DC) -of=$(TARGET) $(ALL_DFLAGS) $(ALL_LDFLAGS) $(LIBS) $(SOURCEFILES)
]]
end
function suite.dmd_linkCmd_separateCompilation()
compilationmodel "File"
prepare_cfg({ m.make.linkCmd })
test.capture [[
LINKCMD = $(DC) -of=$(TARGET) $(ALL_LDFLAGS) $(LIBS) $(OBJECTS)
]]
end
| bsd-3-clause |
CrazyEddieTK/Zero-K | LuaUI/Widgets/gfx_lups_units_on_fire.lua | 5 | 3025 | -- $Id: gfx_lups_units_on_fire.lua 3171 2008-11-06 09:06:29Z det $
function widget:GetInfo()
return {
name = "Units on Fire",
desc = "Graphical effect for burning units",
author = "jK/quantum",
date = "Sep, 2008",
license = "GNU GPL, v2 or later",
layer = 10,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spGetAllUnits = Spring.GetAllUnits
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local flameFX = {
layer = 0,
speed = 0.65,
life = 30,
lifeSpread = 10,
delaySpread = 20,
colormap = {
{0, 0, 0, 0.},
{0.4, 0.4, 0.4, 0.01},
{0.35, 0.15, 0.15, 0.20},
{0, 0, 0, 0}
},
rotSpeed = 1,
rotSpeedSpread = -2,
rotSpread = 360,
sizeSpread = 1,
sizeGrowth = 0.9,
emitVector = {0, 1, 0},
emitRotSpread = 60,
texture = 'bitmaps/GPL/flame.png',
count = 5,
-- fields that differ per instance (here for reference and static tables)
force = {0, 1, 0},
pos = {0, 0, 0},
partpos = "",
size = 1,
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local AddParticles
local GetWind = Spring.GetWind
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitRadius = Spring.GetUnitRadius
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
if not WG.Lups then
widgetHandler:RemoveCallIn("GameFrame")
return
end
AddParticles = WG.Lups.AddParticles
end
local CHECK_INTERVAL = 6
local burningUnits = { count = 0 }
function widget:GameFrame(n)
if n % CHECK_INTERVAL ~= 0 then
return
end
burningUnits.count = 0
local units = spGetAllUnits()
for i = 1, #units do
local unitID = units[i]
if spGetUnitRulesParam(unitID, "on_fire") == 1 then
burningUnits.count = burningUnits.count + 1
burningUnits[burningUnits.count] = unitID
end
end
if burningUnits.count == 0 then
return
end
local wx, wy, wz = GetWind()
flameFX.force[1] = wx * 0.09
flameFX.force[2] = wy * 0.09 + 3
flameFX.force[3] = wz * 0.09
for i = 1, burningUnits.count do
local unitID = burningUnits[i]
local x, y, z = spGetUnitPosition(unitID)
local r = spGetUnitRadius(unitID)
if (r and x) and math.random(400) < (400 - burningUnits.count) then
flameFX.pos[1] = x
flameFX.pos[2] = y
flameFX.pos[3] = z
flameFX.partpos = "r*sin(alpha),0,r*cos(alpha) | alpha=rand()*2*pi, r=rand()*0.6*" .. r
flameFX.size = r * 0.35
AddParticles('SimpleParticles2', flameFX)
end
end
end | gpl-2.0 |
blueyed/awesome | tests/test-awful-rules.lua | 3 | 7371 | local awful = require("awful")
local gears = require("gears")
local beautiful = require("beautiful")
local test_client = require("_client")
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local callback_called = false
-- Magic table to store tests
local tests = {}
local tb_height = gears.math.round(beautiful.get_font_height() * 1.5)
-- local border_width = beautiful.border_width
-- Detect "manage" race conditions
local real_apply = awful.rules.apply
function awful.rules.apply(c)
assert(#c:tags() == 0)
return real_apply(c)
end
local function test_rule(rule)
rule.rule = rule.rule or {}
-- Create a random class. The number need to be large as "rule1" and "rule10" would collide
-- The math.ceil is necessary to remove the floating point, this create an invalid dbus name
local class = string.format("rule%010d", 42+#tests)
rule.rule.class = rule.rule.class or class
test_client(rule.rule.class, rule.properties.name or "Foo")
if rule.test then
local t = rule.test
table.insert(tests, function() return t(rule.rule.class) end)
rule.test = nil
end
table.insert(awful.rules.rules, rule)
end
-- Helper function to search clients
local function get_client_by_class(class)
for _, c in ipairs(client.get()) do
if class == c.class then
return c
end
end
end
-- Test callback and floating
test_rule {
properties = { floating = true },
callback = function(c)
assert(type(c) == "client")
callback_called = true
end,
test = function(class)
-- Test if callbacks works
assert(callback_called)
-- Make sure "smart" dynamic properties are applied
assert(get_client_by_class(class).floating)
-- The size should not have changed
local geo = get_client_by_class(class):geometry()
assert(geo.width == 100 and geo.height == 100+tb_height)
return true
end
}
-- Test ontop
test_rule {
properties = { ontop = true },
test = function(class)
-- Make sure C-API properties are applied
assert(get_client_by_class(class).ontop)
return true
end
}
-- Test placement
test_rule {
properties = {
floating = true,
placement = "bottom_right"
},
test = function(class)
-- Test placement
local sgeo = mouse.screen.workarea
local c = get_client_by_class(class)
local geo = c:geometry()
assert(geo.y+geo.height+2*c.border_width == sgeo.y+sgeo.height)
assert(geo.x+geo.width+2*c.border_width == sgeo.x+sgeo.width)
return true
end
}
-- Create a tag named after the class name
test_rule {
properties = { new_tag=true },
test = function(class)
local c_new_tag1 = get_client_by_class(class)
assert(#c_new_tag1:tags()[1]:clients() == 1)
assert(c_new_tag1:tags()[1].name == class)
return true
end
}
-- Create a tag named Foo Tag with a magnifier layout
test_rule {
properties = {
new_tag = {
name = "Foo Tag",
layout = awful.layout.suit.magnifier
}
},
test = function(class)
local t_new_tag2 = get_client_by_class(class):tags()[1]
assert( #t_new_tag2:clients() == 1 )
assert( t_new_tag2.name == "Foo Tag" )
assert( t_new_tag2.layout.name == "magnifier" )
return true
end
}
-- Create a tag named "Bar Tag"
test_rule {
properties = { new_tag= "Bar Tag" },
test = function(class)
local c_new_tag3 = get_client_by_class(class)
assert(#c_new_tag3:tags()[1]:clients() == 1)
assert(c_new_tag3:tags()[1].name == "Bar Tag")
return true
end
}
-- Test if setting the geometry work
test_rule {
properties = {
floating = true,
x = 200,
y = 200,
width = 200,
height = 200,
},
test = function(class)
local c = get_client_by_class(class)
local geo = c:geometry()
-- Give it some time
if geo.y < 180 then return end
assert(geo.x == 200)
assert(geo.y == 200)
assert(geo.width == 200)
assert(geo.height == 200)
return true
end
}
-- Test if setting a partial geometry preserve the other attributes
test_rule {
properties = {
floating = true,
x = 200,
geometry = {
height = 220
}
},
test = function(class)
local c = get_client_by_class(class)
local geo = c:geometry()
-- Give it some time
if geo.height < 200 then return end
assert(geo.x == 200)
assert(geo.width == 100)
assert(geo.height == 220)
return true
end
}
-- Test maximized_horizontal
test_rule {
properties = { maximized_horizontal = true },
test = function(class)
local c = get_client_by_class(class)
-- Make sure C-API properties are applied
assert(c.maximized_horizontal)
local geo = c:geometry()
local sgeo = c.screen.workarea
assert(geo.x==sgeo.x)
assert(geo.width+2*c.border_width==sgeo.width)
return true
end
}
-- Test maximized_vertical
test_rule {
properties = { maximized_vertical = true },
test = function(class)
local c = get_client_by_class(class)
-- Make sure C-API properties are applied
assert(c.maximized_vertical)
local geo = c:geometry()
local sgeo = c.screen.workarea
assert(geo.y==sgeo.y)
assert(geo.height+2*c.border_width==sgeo.height)
return true
end
}
-- Test fullscreen
test_rule {
properties = { fullscreen = true },
test = function(class)
local c = get_client_by_class(class)
-- Make sure C-API properties are applied
assert(c.fullscreen)
local geo = c:geometry()
local sgeo = c.screen.geometry
assert(geo.x==sgeo.x)
assert(geo.y==sgeo.y)
assert(geo.height+2*c.border_width==sgeo.height)
assert(geo.width+2*c.border_width==sgeo.width)
return true
end
}
-- Test tag and switchtotag
test_rule {
properties = {
tag = "9",
switchtotag = true
},
test = function(class)
local c = get_client_by_class(class)
-- Make sure C-API properties are applied
assert(#c:tags() == 1)
assert(c:tags()[1].name == "9")
assert(c.screen.selected_tag.name == "9")
return true
end
}
test_rule {
properties = {
tag = "8",
switchtotag = false
},
test = function(class)
local c = get_client_by_class(class)
-- Make sure C-API properties are applied
assert(#c:tags() == 1)
assert(c:tags()[1].name == "8")
assert(c.screen.selected_tag.name ~= "8")
return true
end
}
-- Wait until all the auto-generated clients are ready
local function spawn_clients()
if #client.get() >= #tests then
-- Set tiled
awful.layout.inc(1)
return true
end
end
require("_runner").run_steps{spawn_clients, unpack(tests)}
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
minetest-games/Minetest_TNG | mods/tnt/init.lua | 2 | 10690 | tnt = {}
-- Default to enabled in singleplayer and disabled in multiplayer
local singleplayer = minetest.is_singleplayer()
local setting = minetest.setting_getbool("enable_tnt")
if (not singleplayer and setting ~= true) or
(singleplayer and setting == false) then
return
end
-- loss probabilities array (one in X will be lost)
local loss_prob = {}
loss_prob["default:cobble"] = 3
loss_prob["default:dirt"] = 4
local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
-- Fill a list with data for content IDs, after all nodes are registered
local cid_data = {}
minetest.after(0, function()
for name, def in pairs(minetest.registered_nodes) do
cid_data[minetest.get_content_id(name)] = {
name = name,
drops = def.drops,
flammable = def.groups.flammable,
on_blast = def.on_blast,
}
end
end)
local function rand_pos(center, pos, radius)
local def
local reg_nodes = minetest.registered_nodes
local i = 0
repeat
-- Give up and use the center if this takes too long
if i > 4 then
pos.x, pos.z = center.x, center.z
break
end
pos.x = center.x + math.random(-radius, radius)
pos.z = center.z + math.random(-radius, radius)
def = reg_nodes[minetest.get_node(pos).name]
i = i + 1
until def and not def.walkable
end
local function eject_drops(drops, pos, radius)
local drop_pos = vector.new(pos)
for _, item in pairs(drops) do
local count = item:get_count()
local max = item:get_stack_max()
if count > max then
item:set_count(max)
end
while count > 0 do
if count < max then
item:set_count(count)
end
rand_pos(pos, drop_pos, radius)
local obj = minetest.add_item(drop_pos, item)
if obj then
obj:get_luaentity().collect = true
obj:setacceleration({x = 0, y = -10, z = 0})
obj:setvelocity({x = math.random(-3, 3), y = 10,
z = math.random(-3, 3)})
end
count = count - max
end
end
end
local function add_drop(drops, item)
item = ItemStack(item)
local name = item:get_name()
if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
return
end
local drop = drops[name]
if drop == nil then
drops[name] = item
else
drop:set_count(drop:get_count() + item:get_count())
end
end
local fire_node = {name = "fire:basic_flame"}
local function destroy(drops, pos, cid, disable_drops)
if minetest.is_protected(pos, "") then
return
end
local def = cid_data[cid]
if def and def.on_blast then
def.on_blast(vector.new(pos), 1)
return
end
if def and def.flammable then
minetest.set_node(pos, fire_node)
else
minetest.remove_node(pos)
if disable_drops then return end
if def then
local node_drops = minetest.get_node_drops(def.name, "")
for _, item in ipairs(node_drops) do
add_drop(drops, item)
end
end
end
end
local function calc_velocity(pos1, pos2, old_vel, power)
local vel = vector.direction(pos1, pos2)
vel = vector.normalize(vel)
vel = vector.multiply(vel, power)
-- Divide by distance
local dist = vector.distance(pos1, pos2)
dist = math.max(dist, 1)
vel = vector.divide(vel, dist)
-- Add old velocity
vel = vector.add(vel, old_vel)
return vel
end
local function entity_physics(pos, radius)
-- Make the damage radius larger than the destruction radius
local objs = minetest.get_objects_inside_radius(pos, radius)
for _, obj in pairs(objs) do
local obj_pos = obj:getpos()
local obj_vel = obj:getvelocity()
local dist = math.max(1, vector.distance(pos, obj_pos))
if obj_vel ~= nil then
obj:setvelocity(calc_velocity(pos, obj_pos,
obj_vel, radius * 10))
end
local damage = (4 / dist) * radius
obj:set_hp(obj:get_hp() - damage)
end
end
local function add_effects(pos, radius)
minetest.add_particlespawner({
amount = 128,
time = 1,
minpos = vector.subtract(pos, radius / 2),
maxpos = vector.add(pos, radius / 2),
minvel = {x = -20, y = -20, z = -20},
maxvel = {x = 20, y = 20, z = 20},
minacc = vector.new(),
maxacc = vector.new(),
minexptime = 1,
maxexptime = 3,
minsize = 8,
maxsize = 16,
texture = "tnt_smoke.png",
})
end
function tnt.burn(pos)
local name = minetest.get_node(pos).name
local group = minetest.get_item_group(name,"tnt")
if group > 0 then
minetest.sound_play("tnt_ignite", {pos = pos})
minetest.set_node(pos, {name = name .. "_burning"})
minetest.get_node_timer(pos):start(1)
elseif name == "tnt:gunpowder" then
minetest.sound_play("tnt_gunpowder_burning", {pos = pos, max_hear_distance = 8, gain = 2})
minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
minetest.get_node_timer(pos):start(1)
end
end
function tnt.explode(pos, radius, disable_drops)
local pos = vector.round(pos)
local vm = VoxelManip()
local pr = PseudoRandom(os.time())
local p1 = vector.subtract(pos, radius)
local p2 = vector.add(pos, radius)
local minp, maxp = vm:read_from_map(p1, p2)
local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
local data = vm:get_data()
local drops = {}
local p = {}
local c_air = minetest.get_content_id("air")
for z = -radius, radius do
for y = -radius, radius do
local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
for x = -radius, radius do
if (x * x) + (y * y) + (z * z) <=
(radius * radius) + pr:next(-radius, radius) then
local cid = data[vi]
p.x = pos.x + x
p.y = pos.y + y
p.z = pos.z + z
if cid ~= c_air then
destroy(drops, p, cid, disable_drops)
end
end
vi = vi + 1
end
end
end
return drops
end
function tnt.boom(pos, radius, damage_radius, disable_drops)
minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 80})
minetest.set_node(pos, {name = "tnt:boom"})
minetest.get_node_timer(pos):start(0.5)
local drops = tnt.explode(pos, radius, disable_drops)
entity_physics(pos, damage_radius)
if not disable_drops then
eject_drops(drops, pos, radius)
end
add_effects(pos, radius)
end
default.register_node("tnt:boom", {
drawtype = "plantlike",
tiles = {"tnt_boom.png"},
light_source = default.LIGHT_MAX,
walkable = false,
drop = "",
groups = {dig_immediate = 3},
on_timer = function(pos, elapsed)
minetest.remove_node(pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
default.register_node("tnt:gunpowder", {
description = "Gun Powder",
drawtype = "raillike",
paramtype = "light",
is_ground_content = false,
sunlight_propagates = true,
walkable = false,
tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
inventory_image = "tnt_gunpowder_inventory.png",
wield_image = "tnt_gunpowder_inventory.png",
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2 + 1/16, 1/2},
},
groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
sounds = default.node_sound_leaves_defaults(),
on_punch = function(pos, node, puncher)
if puncher:get_wielded_item():get_name() == "default:torch" then
tnt.burn(pos)
end
end,
on_blast = function(pos, intensity)
tnt.burn(pos)
end,
})
default.register_node("tnt:gunpowder_burning", {
drawtype = "raillike",
paramtype = "light",
sunlight_propagates = true,
walkable = false,
light_source = 5,
tiles = {
{
name = "tnt_gunpowder_burning_straight_animated.png",
animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}
},
{
name = "tnt_gunpowder_burning_curved_animated.png",
animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}
},
{
name = "tnt_gunpowder_burning_t_junction_animated.png",
animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}
},
{
name = "tnt_gunpowder_burning_crossing_animated.png",
animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}
}
},
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
drop = "",
groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
sounds = default.node_sound_leaves_defaults(),
on_timer = function(pos, elapsed)
for dx = -1, 1 do
for dz = -1, 1 do
for dy = -1, 1 do
if not (dx == 0 and dz == 0) then
tnt.burn({x = pos.x + dx, y = pos.y + dy, z = pos.z + dz})
end
end
end
end
minetest.remove_node(pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
minetest.register_abm({
nodenames = {"group:tnt", "tnt:gunpowder"},
neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
interval = 1,
chance = 1,
action = tnt.burn,
})
function tnt.register_tnt(name, def)
if not def or not name then
return false
end
if not def.tiles then
def.tiles = {}
end
local tnt_top = def.tiles.top or "tnt_top.png"
local tnt_bottom = def.tiles.bottom or "tnt_bottom.png"
local tnt_side = def.tiles.side or "tnt_side.png"
local tnt_burning = def.tiles.burning or "tnt_top_burning.png"
if not def.damage_radius then
def.damage_radius = def.radius * 2
end
minetest.register_node(":" .. name, {
description = def.description,
tiles = {tnt_top, tnt_bottom, tnt_side},
is_ground_content = false,
groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher)
if puncher:get_wielded_item():get_name() == "default:torch" then
minetest.sound_play("tnt_ignite", {pos=pos})
minetest.set_node(pos, {name = name .. "_burning"})
minetest.get_node_timer(pos):start(4)
end
end,
on_blast = function(pos, intensity)
tnt.burn(pos)
end,
mesecons = {effector = {action_on =
function (pos)
tnt.boom(pos, def.radius, def.damage_radius, def.disable_drops)
end
}
},
})
minetest.register_node(":" .. name .. "_burning", {
tiles = {
{
name = tnt_burning,
animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1}
},
tnt_bottom,
tnt_side
},
light_source = 5,
drop = "",
sounds = default.node_sound_wood_defaults(),
on_timer = function (pos, elapsed)
tnt.boom(pos, def.radius, def.damage_radius, def.disable_drops)
end,
-- unaffected by explosions
on_blast = function() end,
})
end
tnt.register_tnt("tnt:tnt", {
description = "TNT",
radius = radius,
tiles = {burning = "tnt_top_burning_animated.png"},
})
minetest.register_craft({
output = "tnt:gunpowder",
type = "shapeless",
recipe = {"default:coal_lump", "default:gravel"}
})
minetest.register_craft({
output = "tnt:tnt",
recipe = {
{"", "group:wood", ""},
{"group:wood", "tnt:gunpowder", "group:wood"},
{"", "group:wood", ""}
}
})
| gpl-3.0 |
TimSimpson/Macaroni | Main/App/Source/test/lua/Macaroni/Model/ReasonTests.lua | 2 | 2257 | --------------------------------------------------------------------------------
-- Copyright 2011 Tim Simpson
--
-- 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 Axiom = require "Macaroni.Model.Axiom";
local FileName = require "Macaroni.Model.FileName";
local Path = require "Macaroni.IO.Path";
local Reason = require "Macaroni.Model.Reason";
local Source = require "Macaroni.Model.Source";
Test.register(
{
name = "Reason tests.",
tests = {
{
name = "Creating a Reason.",
init = function(this)
this.file = FileName.Create(Path.New("", "Mino.mcpp"));
this.source = Source.Create(this.file, 10, 1);
this.axiom = Axiom.LuaCreate("Class keyword discovered at start of line.");
this.reason = Reason.Create(this.axiom, this.source);
end,
tests = {
["Axiom is what was passed in."] = function(this)
local a = this.reason.Axiom;
Test.assertEquals(this.axiom, a);
end,
["Source is what was passed in."] = function(this)
local src = this.reason.Source;
Test.assertEquals(this.source, src);
end,
["Tostring concats both relevant parts."] = function(this)
Test.assertEquals("Mino.mcpp, line 10, column 1: Class keyword discovered at start of line.",
tostring(this.reason));
end,
}
}
} -- end of all Reason Tests.
}); -- End of register call
| apache-2.0 |
unusualcrow/redead_reloaded | entities/entities/sent_heliflare/init.lua | 1 | 1124 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
ENT.Rotor = Sound("NPC_AttackHelicopter.RotorsLoud")
ENT.Explode = Sound("weapons/flashbang/flashbang_explode1.wav")
function ENT:Initialize()
self:SetModel(Model("models/props_c17/trappropeller_lever.mdl"))
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WEAPON)
self:DrawShadow(false)
self:SetNWFloat("BurnDelay", CurTime() + 3)
local phys = self:GetPhysicsObject()
if IsValid(phys) then
phys:Wake()
phys:SetDamping(0, 10)
end
self.DieTime = CurTime() + 45
end
function ENT:Think()
if self:GetNWFloat("BurnDelay", 0) < CurTime() and not self.Burning then
self.Burning = true
self:EmitSound(self.Rotor)
self:EmitSound(self.Explode, 100, math.random(90, 110))
end
if self.DieTime < CurTime() then
self:Remove()
end
end
function ENT:OnRemove()
self:StopSound(self.Rotor)
end
function ENT:OnTakeDamage(dmginfo)
end
function ENT:PhysicsCollide(data, phys)
end
function ENT:UpdateTransmitState()
return TRANSMIT_ALWAYS
end
| mit |
czfshine/Don-t-Starve | data/DLC0001/scripts/components/edible.lua | 1 | 3916 | local Edible = Class(function(self, inst)
self.inst = inst
self.healthvalue = 10
self.hungervalue = 10
self.sanityvalue = 0
self.foodtype = "GENERIC"
self.oneaten = nil
self.degrades_with_spoilage = true
self.temperaturedelta = 0
self.temperatureduration = 0
self.inst:AddTag("edible")
self.stale_hunger = TUNING.STALE_FOOD_HUNGER
self.stale_health = TUNING.STALE_FOOD_HEALTH
self.spoiled_hunger = TUNING.SPOILED_FOOD_HUNGER
self.spoiled_health = TUNING.SPOILED_FOOD_HEALTH
end)
function Edible:GetSanity(eater)
local ignore_spoilage = not self.degrades_with_spoilage or ((eater and eater.components.eater and eater.components.eater.ignoresspoilage) or self.sanityvalue < 0)
if self.inst.components.perishable and not ignore_spoilage then
if self.inst.components.perishable:IsStale() then
if self.sanityvalue > 0 then
return 0
end
elseif self.inst.components.perishable:IsSpoiled() then
return -TUNING.SANITY_SMALL
end
end
return self.sanityvalue
end
function Edible:GetHunger(eater)
local multiplier = 1
local ignore_spoilage = not self.degrades_with_spoilage or ((eater and eater.components.eater and eater.components.eater.ignoresspoilage) or self.hungervalue < 0)
if self.inst.components.perishable and not ignore_spoilage then
if self.inst.components.perishable:IsStale() then
multiplier = (eater and eater.components.eater and eater.components.eater.stale_hunger) or self.stale_hunger
elseif self.inst.components.perishable:IsSpoiled() then
multiplier = (eater and eater.components.eater and eater.components.eater.spoiled_hunger) or self.spoiled_hunger
end
end
return multiplier*(self.hungervalue)
end
function Edible:GetHealth(eater)
local multiplier = 1
local ignore_spoilage = not self.degrades_with_spoilage or ((eater and eater.components.eater and eater.components.eater.ignoresspoilage) or self.healthvalue < 0)
if self.inst.components.perishable and not ignore_spoilage then
if self.inst.components.perishable:IsStale() then
multiplier = (eater and eater.components.eater and eater.components.eater.stale_health) or self.stale_health
elseif self.inst.components.perishable:IsSpoiled() then
multiplier = (eater and eater.components.eater and eater.components.eater.spoiled_health) or self.spoiled_health
end
end
return multiplier*(self.healthvalue)
end
function Edible:GetDebugString()
return string.format("Food type: %s, health: %2.2f, hunger: %2.2f, sanity: %2.2f",self.foodtype, self.healthvalue, self.hungervalue, self.sanityvalue)
end
function Edible:SetOnEatenFn(fn)
self.oneaten = fn
end
function Edible:OnEaten(eater)
if self.oneaten then
self.oneaten(self.inst, eater)
end
-- Food is an implicit heater/cooler if it has temperature
if self.temperaturedelta ~= 0 and self.temperatureduration ~= 0 and eater and eater.components.temperature then
eater.recent_temperatured_food = self.temperaturedelta
if eater.food_temp_task then eater.food_temp_task:Cancel() end
eater.food_temp_task = eater:DoTaskInTime(self.temperatureduration, function(eater)
eater.recent_temperatured_food = 0
end)
end
self.inst:PushEvent("oneaten", {eater = eater})
end
function Edible:CollectInventoryActions(doer, actions, right)
if doer.components.eater and doer.components.eater:IsValidFood(self.inst) and doer.components.eater:AbleToEat(self.inst) then
if not self.inst.components.equippable or right then
table.insert(actions, ACTIONS.EAT)
end
end
end
function Edible:CollectUseActions(doer, target, actions, right)
if (target.components.eater and target.components.eater:CanEat(self.inst)) and (target.components.inventoryitem and target.components.inventoryitem:IsHeld()) and
target:HasTag("pet") then
table.insert(actions, ACTIONS.FEED)
end
end
return Edible | gpl-2.0 |
matthewhesketh/mattata | plugins/currency.lua | 2 | 1799 | --[[
Based on a plugin by topkecleon. Licensed under GNU AGPLv3
https://github.com/topkecleon/otouto/blob/master/LICENSE.
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local currency = {}
local mattata = require('mattata')
local https = require('ssl.https')
function currency:init()
currency.commands = mattata.commands(self.info.username):command('currency'):command('convert'):command('cash').table
currency.help = '/currency <amount> <from> to <to> - Converts exchange rates for various currencies via Google Finance. Aliases: /convert, /cash.'
currency.url = 'https://www.google.com/finance/converter?from=%s&to=%s&a=%s'
end
function currency.on_message(_, message, _, language)
local input = mattata.input(message.text:upper())
if input then
input = input:gsub('%$', 'USD'):gsub('€', 'EUR'):gsub('£', 'GBP')
end
if not input or not input:match('^.- %a%a%a TO %a%a%a$') then
return mattata.send_reply(message, currency.help)
end
local amount, from, to = input:match('^(.-) (%a%a%a) TO (%a%a%a)$')
amount = tonumber(amount) or 1
local result = 1
if from ~= to then
local str, res = https.request(string.format(currency.url, from, to, amount))
if res ~= 200 then
return mattata.send_reply(message, language.errors.connection)
end
str = str:match('<span class=bld>(.-) %u+</span>')
if not str then
return mattata.send_reply(message, language.errors.results)
end
result = string.format('%.2f', str)
end
result = string.format('%s %s = %s %s', amount, from, result, to)
return mattata.send_message(message.chat.id, result)
end
return currency | mit |
czfshine/Don-t-Starve | data/scripts/map/levels/survival.lua | 1 | 7960 | require("map/level")
----------------------------------
-- Survival levels
----------------------------------
AddLevel(LEVELTYPE.SURVIVAL, {
id="SURVIVAL_DEFAULT",
name=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELS[1],
desc=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELDESC[1],
overrides={
{"start_setpeice", "DefaultStart"},
{"start_node", "Clearing"},
},
tasks = {
"Make a pick",
"Dig that rock",
"Great Plains",
"Squeltch",
"Beeeees!",
"Speak to the king",
"Forest hunters",
},
numoptionaltasks = 4,
optionaltasks = {
"Befriend the pigs",
"For a nice walk",
"Kill the spiders",
"Killer bees!",
"Make a Beehat",
"The hunters",
"Magic meadow",
"Frogs and bugs",
},
set_pieces = {
["ResurrectionStone"] = { count=2, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters" } },
["WormholeGrass"] = { count=8, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters", "Befriend the pigs", "For a nice walk", "Kill the spiders", "Killer bees!", "Make a Beehat", "The hunters", "Magic meadow", "Frogs and bugs"} },
},
ordered_story_setpieces = {
"TeleportatoRingLayout",
"TeleportatoBoxLayout",
"TeleportatoCrankLayout",
"TeleportatoPotatoLayout",
"AdventurePortalLayout",
"TeleportatoBaseLayout",
},
required_prefabs = {
"teleportato_ring", "teleportato_box", "teleportato_crank", "teleportato_potato", "teleportato_base", "chester_eyebone", "adventure_portal"
},
})
if PLATFORM == "PS4" then -- boons and spiders at default values rather than "often"
AddLevel(LEVELTYPE.SURVIVAL, {
id="SURVIVAL_DEFAULT_PLUS",
name=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELS[2],
desc= STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELDESC[2],
overrides={
{"start_setpeice", "DefaultPlusStart"},
{"start_node", {"DeepForest", "Forest", "SpiderForest", "Plain", "Rocky", "Marsh"}},
{"berrybush", "rare"},
{"carrot", "rare"},
{"rabbits", "rare"},
},
tasks = {
"Make a pick",
"Dig that rock",
"Great Plains",
"Squeltch",
"Beeeees!",
"Speak to the king",
"Tentacle-Blocked The Deep Forest",
},
numoptionaltasks = 4,
optionaltasks = {
"Forest hunters",
"Befriend the pigs",
"For a nice walk",
"Kill the spiders",
"Killer bees!",
"Make a Beehat",
"The hunters",
"Magic meadow",
"Hounded Greater Plains",
"Merms ahoy",
"Frogs and bugs",
},
set_pieces = {
["ResurrectionStone"] = { count=2, tasks={ "Speak to the king", "Forest hunters" } },
["WormholeGrass"] = { count=8, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters", "Befriend the pigs", "For a nice walk", "Kill the spiders", "Killer bees!", "Make a Beehat", "The hunters", "Magic meadow", "Frogs and bugs"} },
},
ordered_story_setpieces = {
"TeleportatoRingLayout",
"TeleportatoBoxLayout",
"TeleportatoCrankLayout",
"TeleportatoPotatoLayout",
"AdventurePortalLayout",
"TeleportatoBaseLayout",
},
required_prefabs = {
"teleportato_ring", "teleportato_box", "teleportato_crank", "teleportato_potato", "teleportato_base", "chester_eyebone", "adventure_portal"
},
})
else
AddLevel(LEVELTYPE.SURVIVAL, {
id="SURVIVAL_DEFAULT_PLUS",
name=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELS[2],
desc= STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELDESC[2],
overrides={
{"start_setpeice", "DefaultPlusStart"},
{"start_node", {"DeepForest", "Forest", "SpiderForest", "Plain", "Rocky", "Marsh"}},
{"boons", "often"},
{"spiders", "often"},
{"berrybush", "rare"},
{"carrot", "rare"},
{"rabbits", "rare"},
},
tasks = {
"Make a pick",
"Dig that rock",
"Great Plains",
"Squeltch",
"Beeeees!",
"Speak to the king",
"Tentacle-Blocked The Deep Forest",
},
numoptionaltasks = 4,
optionaltasks = {
"Forest hunters",
"Befriend the pigs",
"For a nice walk",
"Kill the spiders",
"Killer bees!",
"Make a Beehat",
"The hunters",
"Magic meadow",
"Hounded Greater Plains",
"Merms ahoy",
"Frogs and bugs",
},
set_pieces = {
["ResurrectionStone"] = { count=2, tasks={ "Speak to the king", "Forest hunters" } },
["WormholeGrass"] = { count=8, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters", "Befriend the pigs", "For a nice walk", "Kill the spiders", "Killer bees!", "Make a Beehat", "The hunters", "Magic meadow", "Frogs and bugs"} },
},
ordered_story_setpieces = {
"TeleportatoRingLayout",
"TeleportatoBoxLayout",
"TeleportatoCrankLayout",
"TeleportatoPotatoLayout",
"AdventurePortalLayout",
"TeleportatoBaseLayout",
},
required_prefabs = {
"teleportato_ring", "teleportato_box", "teleportato_crank", "teleportato_potato", "teleportato_base", "chester_eyebone", "adventure_portal"
},
})
end
AddLevel(LEVELTYPE.SURVIVAL, {
id="COMPLETE_DARKNESS",
name=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELS[3],
desc= STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELDESC[3],
overrides={
{"start_setpeice", "DarknessStart"},
{"start_node", {"DeepForest", "Forest"}},
{"day", "onlynight"},
},
tasks = {
"Make a pick",
"Dig that rock",
"Great Plains",
"Squeltch",
"Beeeees!",
"Speak to the king",
"Tentacle-Blocked The Deep Forest",
},
numoptionaltasks = 4,
optionaltasks = {
"Forest hunters",
"Befriend the pigs",
"For a nice walk",
"Kill the spiders",
"Killer bees!",
"Make a Beehat",
"The hunters",
"Magic meadow",
"Hounded Greater Plains",
"Merms ahoy",
"Frogs and bugs",
},
set_pieces = {
["ResurrectionStone"] = { count=2, tasks={ "Speak to the king", "Forest hunters" } },
["WormholeGrass"] = { count=8, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters", "Befriend the pigs", "For a nice walk", "Kill the spiders", "Killer bees!", "Make a Beehat", "The hunters", "Magic meadow", "Frogs and bugs"} },
},
ordered_story_setpieces = {
"TeleportatoRingLayout",
"TeleportatoBoxLayout",
"TeleportatoCrankLayout",
"TeleportatoPotatoLayout",
"AdventurePortalLayout",
"TeleportatoBaseLayout",
},
required_prefabs = {
"teleportato_ring", "teleportato_box", "teleportato_crank", "teleportato_potato", "teleportato_base", "chester_eyebone", "adventure_portal"
},
})
-- AddLevel(LEVELTYPE.SURVIVAL, {
-- id="SURVIVAL_CAVEPREVIEW",
-- name=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELS[3],
-- desc=STRINGS.UI.CUSTOMIZATIONSCREEN.PRESETLEVELDESC[3],
-- overrides={
-- {"start_setpeice", "CaveTestStart"},
-- {"start_node", "Clearing"},
-- },
-- tasks = {
-- "Make a pick",
-- "Dig that rock",
-- "Great Plains",
-- "Squeltch",
-- "Beeeees!",
-- "Speak to the king",
-- "Forest hunters",
-- },
-- numoptionaltasks = 4,
-- optionaltasks = {
-- "Befriend the pigs",
-- "For a nice walk",
-- "Kill the spiders",
-- "Killer bees!",
-- "Make a Beehat",
-- "The hunters",
-- "Magic meadow",
-- "Frogs and bugs",
-- },
-- set_pieces = {
-- ["ResurrectionStone"] = { count=2, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters" } },
-- ["WormholeGrass"] = { count=8, tasks={"Make a pick", "Dig that rock", "Great Plains", "Squeltch", "Beeeees!", "Speak to the king", "Forest hunters", "Befriend the pigs", "For a nice walk", "Kill the spiders", "Killer bees!", "Make a Beehat", "The hunters", "Magic meadow", "Frogs and bugs"} },
-- },
-- })
| gpl-2.0 |
Mossop/500pxPublisher.lrplugin | 500pxAPI.lua | 1 | 16793 | --[[ Some Handy Constants ]]--
local CONSUMER_KEY = "";
local CONSUMER_SECRET = ""
local SALT = ""
local LrDate = import "LrDate"
local LrErrors = import "LrErrors"
local LrHttp = import "LrHttp"
local LrMD5 = import "LrMD5"
local LrPathUtils = import "LrPathUtils"
local LrStringUtils = import "LrStringUtils"
local LrTasks = import "LrTasks"
local LrBinding = import "LrBinding"
local LrDialogs = import "LrDialogs"
local LrView = import "LrView"
-- Common shortcuts
local bind = LrView.bind
require "sha1"
local JSON = require "JSON"
function JSON:onDecodeError( message, text, char )
if string.match( text, "Invalid OAuth Request" ) then
LrErrors.throwUserError( "You must grant this Publish Service access to your 500px account. Please edit the settings for this Publish Service and login." )
else
LrErrors.throwUserError( "Oops, somethign went wrong. Try again later. onDecodeError" )
end
end
local logger = import "LrLogger"("500pxPublisher")
logger:enable("logfile")
-- Cocaoa time of 0 is unix time 978307200
local COCOA_TIMESHIFT = 978307200
local REQUEST_TOKEN_URL = "https://api.500px.com/v1/oauth/request_token" -- https://
local AUTHORIZE_TOKEN_URL = "https://api.500px.com/v1/oauth/authorize" -- https://
local ACCESS_TOKEN_URL = "https://api.500px.com/v1/oauth/access_token" -- https://
local CALLBACK_URL = "https://500px.com/apps/lightroom"
local BASE_URL = "https://api.500px.com/v1/" -- https://
local VERSIONCHECK_URL = "https://dlcdn.500px.org/downloads/lightroom/versions.txt"
--[[ Some Handy Helper Functions ]]--
local function oauth_encode( value )
return tostring( string.gsub( value, "[^-._~a-zA-Z0-9]",
function( c )
return string.format( "%%%02x", string.byte( c ) ):upper()
end ) )
end
local function unix_timestamp()
return tostring(COCOA_TIMESHIFT + math.floor(LrDate.currentTime() + 0.5))
end
local function generate_nonce()
return LrMD5.digest( tostring(math.random())
.. tostring(LrDate.currentTime())
.. SALT )
end
--[[ Returns an oAuth athorization header and a query string (or post body). ]]--
local function oauth_sign( method, url, args )
assert( method == "GET" or method == "POST" )
--common oauth parameters
args.oauth_consumer_key = CONSUMER_KEY
args.oauth_timestamp = unix_timestamp()
args.oauth_version = "1.0"
args.oauth_nonce = generate_nonce()
args.oauth_signature_method = "HMAC-SHA1"
local oauth_token_secret = args.oauth_token_secret or ""
args.oauth_token_secret = nil
local data = ""
local query_string = ""
local header = ""
local data_pattern = "%s%s=%s"
local query_pattern = "%s%s=%s"
local header_pattern = "OAuth %s%s=\"%s\""
local keys = {}
for key in pairs( args ) do
table.insert( keys, key )
end
table.sort( keys )
for _, key in ipairs( keys ) do
local value = args[key]
-- url encode the value if it's not an oauth parameter
if string.find( key, "oauth" ) == 1 and key ~= "oauth_callback" then
value = string.gsub( value, " ", "+" )
value = oauth_encode( value )
end
-- oauth encode everything, non oauth parameters get encoded twice
value = oauth_encode( value )
-- build up the base string to sign
data = string.format( data_pattern, data, key, value )
data_pattern = "%s&%s=%s"
-- build up the oauth header and query string
if string.find( key, "oauth" ) == 1 then
header = string.format( header_pattern, header, key, value )
header_pattern = "%s, %s=\"%s\""
else
query_string = string.format( query_pattern, query_string, key, value )
query_pattern = "%s&%s=%s"
end
end
local to_sign = string.format( "%s&%s&%s", method, oauth_encode( url ), oauth_encode( data ) )
local key = string.format( "%s&%s", oauth_encode( CONSUMER_SECRET ), oauth_encode( oauth_token_secret ) )
local hmac_binary = hmac_sha1_binary( key, to_sign )
local hmac_b64 = LrStringUtils.encodeBase64( hmac_binary )
data = string.format( "%s&oauth_signature=%s", data, oauth_encode( hmac_b64 ) )
header = string.format( "%s, oauth_signature=\"%s\"", header, oauth_encode( hmac_b64 ) )
return query_string, { field = "Authorization", value = header }
end
--[[ Does an HTTP request to the given url with the given HTTP method and parameters. Returns the raw response, if the request was successful. Otherwise returns nil and an error message. ]]--
local function call_it( method, url, params, rid )
query_string = ""
auth_header = ""
local query_string, auth_header = oauth_sign( method, url, params )
if rid then
logger:trace( "Query " .. rid .. ": " .. method .. " " .. url .. "?" .. query_string )
end
if method == "POST" then
return LrHttp.post( url, query_string, { auth_header, { field = "Content-Type", value = "application/x-www-form-urlencoded" }, { field = "User-Agent", value = "500px Plugin 1.0" }, { field = "Cookie", value = "GARBAGE" } } )
else
return LrHttp.get( url .. "?" .. query_string, { auth_header, { field = "User-Agent", value = "500px Plugin 0.1.5" } } )
end
end
--[[ Calls the rest method and JSON decodes the response ]]--
local function call_rest_method( propertyTable, method, path, args )
local url = BASE_URL .. path
local args = args or {}
local rid = math.random(99999)
if propertyTable.credentials then
args.oauth_token = propertyTable.credentials.oauth_token
args.oauth_token_secret = propertyTable.credentials.oauth_token_secret
end
local response, headers = call_it( method, url, args, rid )
-- logger:trace( "Query " .. rid .. ": " .. (headers.status or -1) )
if not headers.status then
LrErrors.throwUserError( "Could not connect to 500px. Make sure you are connected to the internet and try again." )
end
if headers.status > 404 then
logger:trace("Api error. Response: " .. response)
LrErrors.throwUserError("Something went wrong, try again later.")
elseif headers.status > 401 then
if response:match("Deactivated user") or response:match("This account is banned or deactivated") then
-- logger:trace("User is banned or deactivated. Response: " .. response)
return headers.status == 403, "banned"
else
-- logger:trace("Request: " .. path .. " Response: " .. response)
return headers.status == 403, "other"
end
end
return headers.status == 200, JSON:decode( response )
end
PxAPI = { }
function PxAPI.encodeString( str )
-- Lightroom uses the unicode LINE SEPARATOR but the API uses to more regular newline.
return string.gsub( str, string.char( 0xE2, 0x80, 0xA8 ), "\n" )
end
function PxAPI.decodeString( str )
-- Lightroom uses the unicode LINE SEPARATOR but the API uses to more regular newline.
return string.gsub( str, "\n", string.char( 0xE2, 0x80, 0xA8 ) )
end
function PxAPI.makeCollectionUrl( domain, path )
if domain and path then
return "https://500px.com/" .. domain .. "/sets/" .. path
end
end
-- function PxAPI.makeSetUrl( user, path )
-- if domain and path then
-- logger:trace( "http://500px.com/" .. user .. "/sets/" .. path )
-- return "http://500px.com/" .. user .. "/sets/" .. path
-- end
-- end
function PxAPI.collectionNameToPath( name )
name = name or ""
return tostring( string.gsub( tostring( string.gsub( name, "[^a-zA-Z0-9]+", "_" ) ), "%a", string.lower ) )
end
function PxAPI.getPhotos( propertyTable, args )
return call_rest_method( propertyTable, "GET", "photos", args)
end
function PxAPI.getPhoto( propertyTable, args )
local path = "photos"
if args.photo_id ~= nil then
path = string.format( "photos/%i", args.photo_id )
args.photo_id = nil
return call_rest_method( propertyTable, "GET", path, args )
end
end
function PxAPI.postPhoto( propertyTable, args )
local path = "photos"
if args and args.photo_id then
path = string.format( "photos/%i", args.photo_id )
args.photo_id = nil
args._method = "PUT"
end
return call_rest_method( propertyTable, "POST", path, args )
end
function PxAPI.deletePhoto( propertyTable, args )
path = string.format( "photos/%i", args.photo_id )
args.photo_id = nil
args._method = "DELETE"
return call_rest_method( propertyTable, "POST", path, args )
end
function PxAPI.upload( args )
local url = "https://media.500px.com/upload"
url = string.format("%s?upload_key=%s&photo_id=%s&consumer_key=%s&access_key=%s", url, args.upload_key, args.photo_id, CONSUMER_KEY, args.access_key)
local filePath = assert( args.file_path )
local fileName = LrPathUtils.leafName( filePath )
args.file_path = nil
local mimeChunks = {}
mimeChunks[ #mimeChunks + 1 ] = {
name= "file",
fileName = fileName,
filePath = filePath,
contentType = "application/octet-stream",
}
local response, headers = LrHttp.postMultipart( url, mimeChunks )
if not response or headers.status ~= 200 then
logger:trace( "Upload failed: " .. ( headers.status or "-1" ) )
return false, {}
end
return true, {}
end
function PxAPI.getComments( propertyTable, args )
local path = string.format( "photos/%i/comments", args.photo_id )
args.photo_id = nil
return call_rest_method( propertyTable, "GET", path, args )
end
function PxAPI.postComment( propertyTable, args )
local path = string.format( "photos/%i/comments", args.photo_id )
args.photo_id = nil
return call_rest_method( propertyTable, "POST", path, args )
end
function PxAPI.getUser( propertyTable, args )
call_it( "POST", "https://500px.com/logout", { _method = "delete" } )
return call_rest_method( propertyTable, "GET", "users", args )
end
function PxAPI.getCollections( propertyTable, args )
return call_rest_method( propertyTable, "GET", "collections", args )
end
function PxAPI.postCollection( propertyTable, args )
local path = "collections"
if args and args.collection_id then
path = string.format( "collections/%s", tostring( args.collection_id ) )
args.collection_id = nil
args._method = "PUT"
else
args._method = nil
end
return call_rest_method( propertyTable, "POST", path, args )
end
function PxAPI.deleteCollection( propertyTable, args )
path = string.format( "collections/%i", args.collection_id )
args.collection_id = nil
args._method = "delete"
return call_rest_method( propertyTable, "POST", path, args )
end
function PxAPI.processTags( new_tags, previous_tags, web_tags )
tags = {}
to_remove = {}
to_add = {}
existing = {}
for t in string.gfind( new_tags, "[^,]+" ) do
t = t:match( "^%s*(.-)%s*$" )
tags[ t ] = true
end
if previous_tags then
for t in string.gfind( previous_tags, "[^,]+" ) do
t = t:match( "^%s*(.-)%s*$" )
if not tags[t] then
to_remove[ #to_remove + 1 ] = t
else
existing[ t ] = true
end
end
end
for t in string.gfind( new_tags, "[^,]+" ) do
t = t:match( "^%s*(.-)%s*$" )
if not existing[ t ] then
to_add[ #to_add + 1 ] = t
end
end
return { to_add = to_add, to_remove = to_remove }
end
function PxAPI.setPhotoTags( propertyTable, args )
path = string.format( "photos/%i/tags", args.photo_id )
tags = PxAPI.processTags( args.tags, args.previous_tags )
if #tags.to_remove > 0 then
call_rest_method( propertyTable, "POST", path, { photo_id = args.photo_id, _method = "delete", tags = table.concat( tags.to_remove, "," ) } )
end
if #tags.to_add > 0 then
call_rest_method( propertyTable, "POST", path, { id = args.photo_id, tags = table.concat( tags.to_add, "," ) } )
end
return true, nil
end
function PxAPI.login( context )
call_it( "POST", "https://500px.com/logout", { _method = "delete" } )
-- get a request token
local response, headers = call_it( "POST", REQUEST_TOKEN_URL, { oauth_callback = CALLBACK_URL }, math.random(99999) )
if not response or not headers.status then
LrErrors.throwUserError( "Could not connect to 500px.com. Please make sure you are connected to the internet and try again." )
end
local token = response:match( "oauth_token=([^&]+)" )
local token_secret = response:match( "oauth_token_secret=([^&]+)" )
if not token or not token_secret then
if response:match("Deactivated user") then
logger:trace( "User is banned or deactivated.")
LrErrors.throwUserError( "Sorry, this user is inactive or banned. If you think this is a mistake — please contact us by email: help@500px.com." )
end
LrErrors.throwUserError( "Oops, something went wrong. Try again later.")
end
local url = AUTHORIZE_TOKEN_URL .. string.format( "?oauth_token=%s", token )
LrHttp.openUrlInBrowser(url)
local properties = LrBinding.makePropertyTable( context )
local f = LrView.osFactory()
local contents = f:column {
bind_to_object = properties,
spacing = f:control_spacing(),
f:picture {
value = _PLUGIN:resourceId( "login.png" )
},
f:static_text {
title = "Enter the verification token provided by the website",
place_horizontal = 0.5,
},
f:edit_field {
width = 300,
value = bind "verifier",
place_horizontal = 0.5,
},
}
PxAPI.URLCallback = function( oauth_token, oauth_verifier )
if oauth_token == token then
properties.verifier = oauth_verifier
LrDialogs.stopModalWithResult(contents, "ok")
end
end
local action = LrDialogs.presentModalDialog( {
title = "Enter verification token",
contents = contents,
actionVerb = "Authorize"
} )
PxAPI.URLCallback = nil
if action == "cancel" then return nil end
-- get an access token_secret
local args = {
oauth_token = token,
oauth_token_secret = token_secret,
oauth_verifier = LrStringUtils.trimWhitespace(properties.verifier),
}
local response, headers = call_it( "POST", ACCESS_TOKEN_URL, args, math.random(99999) )
if not response or not headers.status then
LrErrors.throwUserError( "Could not connect to 500px.com. Please make sure you are connected to the internet and try again." )
end
local access_token = response:match( "oauth_token=([^&]+)" )
local access_token_secret = response:match( "oauth_token_secret=([^&]+)" )
if not access_token or not access_token_secret then
if response:match("Deactivated user") then
logger:trace( "User is banned or deactivated.")
LrErrors.throwUserError( "Sorry, this user is inactive or banned. If you think this is a mistake — please contact us by email: help@500px.com." )
else
LrErrors.throwUserError( "Login failed." )
end
end
return {
oauth_token = access_token,
oauth_token_secret = access_token_secret,
}
end
function PxAPI.register( userInfo )
local success, obj = call_rest_method( {}, "POST", "users", {
username = userInfo.username,
password = userInfo.password,
email = userInfo.email,
} )
if success then
call_it( "POST", "https://500px.com/logout", { _method = "delete" } )
-- get a request token
local response, headers = call_it( "POST", REQUEST_TOKEN_URL, { oauth_callback = "oob" }, math.random(99999) )
if not response or not headers.status then
return false, { created = true }
end
local token = response:match( "oauth_token=([^&]+)" )
local token_secret = response:match( "oauth_token_secret=([^&]+)" )
if not token or not token_secret then
return false, { created = true }
end
-- get an access token_secret
local args = {
x_auth_mode = "client_auth",
x_auth_username = userInfo.username,
x_auth_password = userInfo.password,
oauth_token = token,
oauth_token_secret = token_secret,
}
local response, headers = call_it( "POST", ACCESS_TOKEN_URL, args, math.random(99999) )
if not response or not headers.status then
return false, { created = true }
end
local access_token = response:match( "oauth_token=([^&]+)" )
local access_token_secret = response:match( "oauth_token_secret=([^&]+)" )
if not access_token or not access_token_secret then
return false, { created = true }
end
return true, {
oauth_token = access_token,
oauth_token_secret = access_token_secret,
}
else
return false, obj
end
end
function compareVersionPart( a, b, part )
return a[part] - b[part]
end
function PxAPI.compareVersions( a, b )
local check = compareVersionPart( a, b, "major" )
if check ~= 0 then
return check
end
check = compareVersionPart( a, b, "minor" )
if check ~= 0 then
return check
end
return compareVersionPart( a, b, "revision" )
end
function PxAPI.getLatestVersion()
local version = {}
local result = LrHttp.get( VERSIONCHECK_URL )
if result then
-- Assumes the first version is the latest version
local space = result:find( " " )
if space == nil then
return nil
end
versionStr = result:sub( 1, space - 1 )
local start = 1
local dot = versionStr:find( ".", start, true )
if dot == nil then
return nil
end
version["major"] = tonumber( versionStr:sub( start, dot - 1 ) )
start = dot + 1
dot = versionStr:find( ".", start, true )
if dot == nil then
return nil
end
version["minor"] = tonumber( versionStr:sub( start, dot -1 ) )
start = dot + 1
version["revision"] = tonumber( versionStr:sub( start ) )
return version
else
return nil
end
end
| gpl-3.0 |
mohammad8/test1 | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaUI/Widgets/gui_chili_facbar.lua | 5 | 19680 | -------------------------------------------------------------------------------
local version = "v0.053"
function widget:GetInfo()
return {
name = "Chili FactoryBar",
desc = version .. " - Chili buildmenu for factories.",
author = "CarRepairer (converted from jK's Buildbar)",
date = "2010-11-10",
license = "GNU GPL, v2 or later",
layer = 1001,
enabled = false,
}
end
include("Widgets/COFCTools/ExportUtilities.lua")
VFS.Include("LuaRules/Configs/customcmds.h.lua")
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
WhiteStr = "\255\255\255\255"
GreyStr = "\255\210\210\210"
GreenStr = "\255\092\255\092"
local buttonColor = {0,0,0,0.5}
local queueColor = {0.0,0.4,0.4,0.9}
local progColor = {1,0.7,0,0.6}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Chili
local Button
local Label
local Window
local StackPanel
local Grid
local TextBox
local Image
local Progressbar
local screen0
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local window_facbar, stack_main
local echo = Spring.Echo
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local function RecreateFacbar() end
options_path = 'Settings/HUD Panels/FactoryBar'
options = {
maxVisibleBuilds = {
type = 'number',
name = 'Visible Units in Que',
desc = "The maximum units to show in the factory's queue",
min = 2, max = 14,
value = 5,
},
buttonsize = {
type = 'number',
name = 'Button Size',
min = 40, max = 100, step=5,
value = 50,
OnChange = function() RecreateFacbar() end,
},
}
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local EMPTY_TABLE = {}
-- list and interface vars
local facs = {}
local unfinished_facs = {}
local pressedFac = -1
local waypointFac = -1
local waypointMode = 0 -- 0 = off; 1=lazy; 2=greedy (greedy means: you have to left click once before leaving waypoint mode and you can have units selected)
local myTeamID = 0
local inTweak = false
local leftTweak, enteredTweak = false, false
local cycle_half_s = 1
local cycle_2_s = 1
-------------------------------------------------------------------------------
-- SOUNDS
-------------------------------------------------------------------------------
local sound_waypoint = LUAUI_DIRNAME .. 'Sounds/buildbar_waypoint.wav'
local sound_click = LUAUI_DIRNAME .. 'Sounds/buildbar_click.WAV'
local sound_queue_add = LUAUI_DIRNAME .. 'Sounds/buildbar_add.wav'
local sound_queue_rem = LUAUI_DIRNAME .. 'Sounds/buildbar_rem.wav'
-------------------------------------------------------------------------------
local image_repeat = LUAUI_DIRNAME .. 'Images/repeat.png'
local teamColors = {}
local GetTeamColor = Spring.GetTeamColor or function (teamID)
local color = teamColors[teamID]
if (color) then return unpack(color) end
local _,_,_,_,_,_,r,g,b = Spring.GetTeamInfo(teamID)
teamColors[teamID] = {r,g,b}
return r,g,b
end
-------------------------------------------------------------------------------
-- SCREENSIZE FUNCTIONS
-------------------------------------------------------------------------------
local vsx, vsy = widgetHandler:GetViewSizes()
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
end
-------------------------------------------------------------------------------
local GetUnitDefID = Spring.GetUnitDefID
local GetUnitHealth = Spring.GetUnitHealth
local DrawUnitCommands = Spring.DrawUnitCommands
local GetSelectedUnits = Spring.GetSelectedUnits
local GetFullBuildQueue = Spring.GetFullBuildQueue
local GetUnitIsBuilding = Spring.GetUnitIsBuilding
local push = table.insert
-------------------------------------------------------------------------------
local function GetBuildQueue(unitID)
local result = {}
local queue = GetFullBuildQueue(unitID)
if (queue ~= nil) then
for _,buildPair in ipairs(queue) do
local udef, count = next(buildPair, nil)
if result[udef]~=nil then
result[udef] = result[udef] + count
else
result[udef] = count
end
end
end
return result
end
local function UpdateFac(i, facInfo)
--local unitDefID = facInfo.unitDefID
local unitBuildDefID = -1
local unitBuildID = -1
-- building?
local progress = 0
unitBuildID = GetUnitIsBuilding(facInfo.unitID)
if unitBuildID then
unitBuildDefID = GetUnitDefID(unitBuildID)
_, _, _, _, progress = GetUnitHealth(unitBuildID)
--unitDefID = unitBuildDefID
--[[
elseif (unfinished_facs[facInfo.unitID]) then
_, _, _, _, progress = GetUnitHealth(facInfo.unitID)
if (progress>=1) then
progress = -1
unfinished_facs[facInfo.unitID] = nil
end
--]]
end
local buildList = facInfo.buildList
local buildQueue = GetBuildQueue(facInfo.unitID)
for j,unitDefIDb in ipairs(buildList) do
local unitDefIDb = unitDefIDb
if not facs[i].boStack then
echo('<Chili Facbar> Strange error #1' )
else
local boButton = facs[i].boStack.childrenByName[unitDefIDb]
local qButton = facs[i].qStore[i .. '|' .. unitDefIDb]
local boBar = boButton.childrenByName['bp'].childrenByName['prog']
local qBar = qButton.childrenByName['bp'].childrenByName['prog']
local amount = buildQueue[unitDefIDb] or 0
local boCount = boButton.childrenByName['count']
local qCount = qButton.childrenByName['count']
facs[i].qStack:RemoveChild(qButton)
boBar:SetValue(0)
qBar:SetValue(0)
if unitDefIDb == unitBuildDefID then
boBar:SetValue(progress)
qBar:SetValue(progress)
end
if amount > 0 then
boButton.backgroundColor = queueColor
else
boButton.backgroundColor = buttonColor
end
boButton:Invalidate()
boCount:SetCaption(amount > 0 and amount or '')
qCount:SetCaption(amount > 0 and amount or '')
end
end
end
local function UpdateFacQ(i, facInfo)
local unitBuildDefID = -1
local unitBuildID = -1
-- building?
local progress = 0
unitBuildID = GetUnitIsBuilding(facInfo.unitID)
if unitBuildID then
unitBuildDefID = GetUnitDefID(unitBuildID)
_, _, _, _, progress = GetUnitHealth(unitBuildID)
end
local buildQueue = Spring.GetFullBuildQueue(facInfo.unitID, options.maxVisibleBuilds.value +1)
if (buildQueue ~= nil) then
local n,j = 1,options.maxVisibleBuilds.value
while (buildQueue[n]) do
local unitDefIDb, count = next(buildQueue[n], nil)
local qButton = facs[i].qStore[i .. '|' .. unitDefIDb]
if not facs[i].qStack:GetChildByName(qButton.name) then
facs[i].qStack:AddChild(qButton)
end
j = j-1
if j==0 then break end
n = n+1
end
end
end
local function AddFacButton(unitID, unitDefID, tocontrol, stackname)
tocontrol:AddChild(
Button:New{
width = options.buttonsize.value*1.2,
height = options.buttonsize.value*1.0,
tooltip = WG.Translate("interface", "lmb") .. ' - ' .. GreenStr .. WG.Translate("interface", "select") .. '\n'
.. WhiteStr .. WG.Translate("interface", "mmb") .. ' - ' .. GreenStr .. WG.Translate("interface", "go_to") .. '\n'
.. WhiteStr .. WG.Translate("interface", "rmb") .. ' - ' .. GreenStr .. WG.Translate("interface", "quick_rallypoint_mode")
,
backgroundColor = buttonColor,
OnClick = {
unitID ~= 0 and
function(_,_,_,button)
if button == 2 then
local x,y,z = Spring.GetUnitPosition(unitID)
SetCameraTarget(x,y,z)
elseif button == 3 then
Spring.Echo("FactoryBar: Entered easy waypoint mode")
Spring.PlaySoundFile(sound_waypoint, 1, 'ui')
waypointMode = 2 -- greedy mode
waypointFac = stackname
else
Spring.PlaySoundFile(sound_click, 1, 'ui')
Spring.SelectUnitArray({unitID})
end
end
or nil
},
padding={3, 3, 3, 3},
--margin={0, 0, 0, 0},
children = {
unitID ~= 0 and
Image:New {
file = "#"..unitDefID,
file2 = WG.GetBuildIconFrame(UnitDefs[unitDefID]),
keepAspect = false;
width = '100%',
height = '100%',
}
or nil,
},
}
)
local boStack = StackPanel:New{
name = stackname .. '_bo',
itemMargin={0,0,0,0},
itemPadding={0,0,0,0},
padding={0,0,0,0},
--margin={0, 0, 0, 0},
x=0,
width=700,
height = options.buttonsize.value,
resizeItems = false,
orientation = 'horizontal',
centerItems = false,
}
local qStack = StackPanel:New{
name = stackname .. '_q',
itemMargin={0,0,0,0},
itemPadding={0,0,0,0},
padding={0,0,0,0},
--margin={0, 0, 0, 0},
x=0,
width=700,
height = options.buttonsize.value,
resizeItems = false,
orientation = 'horizontal',
centerItems = false,
}
local qStore = {}
local facStack = StackPanel:New{
name = stackname,
itemMargin={0,0,0,0},
itemPadding={0,0,0,0},
padding={0,0,0,0},
--margin={0, 0, 0, 0},
width=800,
height = options.buttonsize.value*1.0,
resizeItems = false,
centerItems = false,
}
facStack:AddChild( qStack )
tocontrol:AddChild( facStack )
return facStack, boStack, qStack, qStore
end
local function MakeButton(unitDefID, facID, facIndex)
local ud = UnitDefs[unitDefID]
local tooltip = "Build Unit: " .. ud.humanName .. " - " .. ud.tooltip .. "\n"
return
Button:New{
name = unitDefID,
tooltip=tooltip,
x=0,
caption='',
width = options.buttonsize.value,
height = options.buttonsize.value,
padding = {4, 4, 4, 4},
--padding = {0,0,0,0},
--margin={0, 0, 0, 0},
backgroundColor = queueColor,
OnClick = {
function(_,_,_,button)
local alt, ctrl, meta, shift = Spring.GetModKeyState()
local rb = button == 3
local lb = button == 1
if not (lb or rb) then return end
local opt = 0
if alt then opt = opt + CMD.OPT_ALT end
if ctrl then opt = opt + CMD.OPT_CTRL end
if meta then opt = opt + CMD.OPT_META end
if shift then opt = opt + CMD.OPT_SHIFT end
if rb then opt = opt + CMD.OPT_RIGHT end
Spring.GiveOrderToUnit(facID, -(unitDefID), EMPTY_TABLE, opt)
if rb then
Spring.PlaySoundFile(sound_queue_rem, 0.97, 'ui')
else
Spring.PlaySoundFile(sound_queue_add, 0.95, 'ui')
end
--UpdateFac(facIndex, facs[facIndex])
end
},
children = {
Label:New {
name='count',
autosize=false;
width="100%";
height="100%";
align="right";
valign="top";
caption = '';
fontSize = 14;
fontShadow = true;
},
Label:New{ caption = ud.metalCost .. ' m', fontSize = 11, x=2, bottom=2, fontShadow = true, },
Image:New {
name = 'bp',
file = "#"..unitDefID,
file2 = WG.GetBuildIconFrame(ud),
keepAspect = false;
width = '100%',height = '80%',
children = {
Progressbar:New{
value = 0.0,
name = 'prog';
max = 1;
color = progColor,
backgroundColor = {1,1,1, 0.01},
x=4,y=4, bottom=4,right=4,
skin=nil,
skinName='default',
},
},
},
},
}
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local function WaypointHandler(x,y,button)
if (button==1)or(button>3) then
Spring.Echo("FactoryBar: Exited easy waypoint mode")
Spring.PlaySoundFile(sound_waypoint, 1, 'ui')
waypointFac = -1
waypointMode = 0
return
end
local alt, ctrl, meta, shift = Spring.GetModKeyState()
local opt = CMD.OPT_RIGHT
if alt then opt = opt + CMD.OPT_ALT end
if ctrl then opt = opt + CMD.OPT_CTRL end
if meta then opt = opt + CMD.OPT_META end
if shift then opt = opt + CMD.OPT_SHIFT end
local type,param = Spring.TraceScreenRay(x,y)
if type=='ground' then
Spring.GiveOrderToUnit(facs[waypointFac].unitID, CMD_RAW_MOVE,param,opt)
elseif type=='unit' then
Spring.GiveOrderToUnit(facs[waypointFac].unitID, CMD.GUARD,{param},opt)
else --feature
type,param = Spring.TraceScreenRay(x,y,true)
Spring.GiveOrderToUnit(facs[waypointFac].unitID, CMD_RAW_MOVE,param,opt)
end
--if not shift then waypointMode = 0; return true end
end
RecreateFacbar = function()
enteredTweak = false
if inTweak then return end
stack_main:ClearChildren()
for i,facInfo in ipairs(facs) do
local unitDefID = facInfo.unitDefID
local unitBuildDefID = -1
local unitBuildID = -1
local progress
-- building?
unitBuildID = GetUnitIsBuilding(facInfo.unitID)
if unitBuildID then
unitBuildDefID = GetUnitDefID(unitBuildID)
_, _, _, _, progress = GetUnitHealth(unitBuildID)
unitDefID = unitBuildDefID
elseif (unfinished_facs[facInfo.unitID]) then
_, _, _, _, progress = GetUnitHealth(facInfo.unitID)
if (progress>=1) then
progress = -1
unfinished_facs[facInfo.unitID] = nil
end
end
local facStack, boStack, qStack, qStore = AddFacButton(facInfo.unitID, unitDefID, stack_main, i)
facs[i].facStack = facStack
facs[i].boStack = boStack
facs[i].qStack = qStack
facs[i].qStore = qStore
local buildList = facInfo.buildList
local buildQueue = GetBuildQueue(facInfo.unitID)
for j,unitDefIDb in ipairs(buildList) do
local unitDefIDb = unitDefIDb
boStack:AddChild( MakeButton(unitDefIDb, facInfo.unitID, i) )
qStore[i .. '|' .. unitDefIDb] = MakeButton(unitDefIDb, facInfo.unitID, i)
end
end
stack_main:Invalidate()
stack_main:UpdateLayout()
end
local function UpdateFactoryList()
facs = {}
local teamUnits = Spring.GetTeamUnits(myTeamID)
local totalUnits = #teamUnits
for num = 1, totalUnits do
local unitID = teamUnits[num]
local unitDefID = GetUnitDefID(unitID)
if UnitDefs[unitDefID].isFactory then
local bo = UnitDefs[unitDefID] and UnitDefs[unitDefID].buildOptions
if bo and #bo > 0 then
push(facs,{ unitID=unitID, unitDefID=unitDefID, buildList=UnitDefs[unitDefID].buildOptions })
local _, _, _, _, buildProgress = GetUnitHealth(unitID)
if (buildProgress)and(buildProgress<1) then
unfinished_facs[unitID] = true
end
end
end
end
RecreateFacbar()
end
------------------------------------------------------
function widget:DrawWorld()
-- Draw factories command lines
if waypointMode>1 then
local unitID
if waypointMode>1 then
unitID = facs[waypointFac].unitID
end
DrawUnitCommands(unitID)
end
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (unitTeam ~= myTeamID) then
return
end
if UnitDefs[unitDefID].isFactory then
local bo = UnitDefs[unitDefID] and UnitDefs[unitDefID].buildOptions
if bo and #bo > 0 then
push(facs,{ unitID=unitID, unitDefID=unitDefID, buildList=UnitDefs[unitDefID].buildOptions })
--UpdateFactoryList()
RecreateFacbar()
end
end
unfinished_facs[unitID] = true
end
function widget:UnitGiven(unitID, unitDefID, unitTeam, oldTeam)
widget:UnitCreated(unitID, unitDefID, unitTeam)
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
if (unitTeam ~= myTeamID) then
return
end
if UnitDefs[unitDefID].isFactory then
for i,facInfo in ipairs(facs) do
if unitID==facInfo.unitID then
table.remove(facs,i)
unfinished_facs[unitID] = nil
--UpdateFactoryList()
RecreateFacbar()
return
end
end
end
end
function widget:UnitTaken(unitID, unitDefID, unitTeam, newTeam)
widget:UnitDestroyed(unitID, unitDefID, unitTeam)
end
function widget:Update()
if myTeamID~=Spring.GetMyTeamID() then
myTeamID = Spring.GetMyTeamID()
UpdateFactoryList()
end
inTweak = widgetHandler:InTweakMode()
cycle_half_s = (cycle_half_s % 16) + 1
cycle_2_s = (cycle_2_s % (32*2)) + 1
if cycle_half_s == 1 then
for i,facInfo in ipairs(facs) do
if Spring.ValidUnitID( facInfo.unitID ) then
if cycle_2_s == 1 then
UpdateFac(i, facInfo)
end
UpdateFacQ(i, facInfo)
end
end
end
if inTweak and not enteredTweak then
enteredTweak = true
stack_main:ClearChildren()
for i = 1,5 do
local facStack, boStack, qStack, qStore = AddFacButton(0, 0, stack_main, i)
end
stack_main:Invalidate()
stack_main:UpdateLayout()
leftTweak = true
end
if not inTweak and leftTweak then
enteredTweak = false
leftTweak = false
RecreateFacbar()
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function widget:SelectionChanged(selectedUnits)
if facs[pressedFac] then
local qStack = facs[pressedFac].qStack
local boStack = facs[pressedFac].boStack
facs[pressedFac].facStack:RemoveChild(boStack)
facs[pressedFac].facStack:AddChild(qStack)
end
pressedFac = -1
if (#selectedUnits == 1) then
for cnt, f in ipairs(facs) do
if f.unitID == selectedUnits[1] then
pressedFac = cnt
local qStack = facs[pressedFac].qStack
local boStack = facs[pressedFac].boStack
facs[pressedFac].facStack:RemoveChild(qStack)
facs[pressedFac].facStack:AddChild(boStack)
end
end
end
end
function widget:MouseRelease(x, y, button)
if (waypointMode>0)and(not inTweak) and (waypointMode>0)and(waypointFac>0) then
WaypointHandler(x,y,button)
end
return -1
end
function widget:MousePress(x, y, button)
if waypointMode>1 then
-- greedy waypointMode
return (button~=2) -- we allow middle click scrolling in greedy waypoint mode
end
if waypointMode>1 then
Spring.Echo("FactoryBar: Exited easy waypoint mode")
Spring.PlaySoundFile(sound_waypoint, 1, 'ui')
end
waypointFac = -1
waypointMode = 0
return false
end
function widget:Initialize()
if (not WG.Chili) then
widgetHandler:RemoveWidget(widget)
return
end
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Window = Chili.Window
StackPanel = Chili.StackPanel
Grid = Chili.Grid
TextBox = Chili.TextBox
Image = Chili.Image
Progressbar = Chili.Progressbar
screen0 = Chili.Screen0
stack_main = Grid:New{
y=20,
padding = {0,0,0,0},
itemPadding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0},
width='100%',
height = '100%',
resizeItems = false,
orientation = 'horizontal',
centerItems = false,
columns=2,
}
window_facbar = Window:New{
padding = {3,3,3,3,},
dockable = true,
name = "facbar",
x = 0, y = "30%",
width = 600,
height = 200,
parent = Chili.Screen0,
draggable = false,
tweakDraggable = true,
tweakResizable = true,
resizable = false,
dragUseGrip = false,
minWidth = 56,
minHeight = 56,
color = {0,0,0,0},
children = {
Label:New{ caption = WG.Translate("interface", "factories"), fontShadow = true, },
stack_main,
},
OnMouseDown={ function(self)
local alt, ctrl, meta, shift = Spring.GetModKeyState()
if not meta then return false end
WG.crude.OpenPath(options_path)
WG.crude.ShowMenu()
return true
end },
}
myTeamID = Spring.GetMyTeamID()
UpdateFactoryList()
local viewSizeX, viewSizeY = widgetHandler:GetViewSizes()
self:ViewResize(viewSizeX, viewSizeY)
end
| gpl-2.0 |
starkos/premake-core | modules/self-test/test_helpers.lua | 15 | 1665 | ---
-- test_helpers.lua
--
-- Helper functions for setting up workspaces and projects, etc.
--
-- Author Jason Perkins
-- Copyright (c) 2008-2016 Jason Perkins and the Premake project.
---
local p = premake
local m = p.modules.self_test
function m.createWorkspace()
local wks = workspace("MyWorkspace")
configurations { "Debug", "Release" }
local prj = m.createProject(wks)
return wks, prj
end
-- Eventually we'll want to deprecate this one and move everyone
-- over to createWorkspace() instead (4 Sep 2015).
function m.createsolution()
local wks = workspace("MySolution")
configurations { "Debug", "Release" }
local prj = m.createproject(wks)
return wks, prj
end
function m.createProject(wks)
local n = #wks.projects + 1
if n == 1 then n = "" end
local prj = project ("MyProject" .. n)
language "C++"
kind "ConsoleApp"
return prj
end
function m.createGroup(wks)
local prj = group ("MyGroup" .. (#wks.groups + 1))
return prj
end
function m.getWorkspace(wks)
p.oven.bake()
return p.global.getWorkspace(wks.name)
end
function m.getRule(name)
p.oven.bake()
return p.global.getRule(name)
end
function m.getProject(wks, i)
wks = m.getWorkspace(wks)
return p.workspace.getproject(wks, i or 1)
end
function m.getConfig(prj, buildcfg, platform)
local wks = m.getWorkspace(prj.workspace)
prj = p.workspace.getproject(wks, prj.name)
return p.project.getconfig(prj, buildcfg, platform)
end
m.print = print
p.alias(m, "createProject", "createproject")
p.alias(m, "getConfig", "getconfig")
p.alias(m, "getProject", "getproject")
p.alias(m, "getWorkspace", "getsolution")
| bsd-3-clause |
rzh/mongocraft | world/Plugins/Core/time.lua | 6 | 5541 | -- Implements time related commands and console commands
local PlayerTimeAddCommandUsage = "Usage: /time add <value> [world]"
local PlayerTimeSetCommandUsage = "Usage: /time set <day|night|value> [world]"
local ConsoleSetTimeCommandUsage = "Usage: time set <day|night|value> [world]"
local ConsoleAddTimeCommandUsage = "Usage: time add <value> [world]"
-- Times of day and night as defined in vanilla minecraft
local SpecialTimesTable = {
["day"] = 1000,
["night"] = 1000 + 12000,
}
-- Used to animate the transition between previous and new times
local function SetTime( World, TimeToSet )
local CurrentTime = World:GetTimeOfDay()
local MaxTime = 24000
-- Handle the cases where TimeToSet < 0 or > 24000
TimeToSet = TimeToSet % MaxTime
local AnimationForward = true
local AnimationSpeed = 480
if CurrentTime > TimeToSet then
AnimationForward = false
AnimationSpeed = -AnimationSpeed
end
local function DoAnimation()
local TimeOfDay = World:GetTimeOfDay()
if AnimationForward then
if TimeOfDay < TimeToSet and (MaxTime - TimeToSet) > AnimationSpeed then -- Without the second check the animation can get stuck in a infinite loop
World:SetTimeOfDay(TimeOfDay + AnimationSpeed)
World:ScheduleTask(1, DoAnimation)
else
World:SetTimeOfDay(TimeToSet) -- Make sure we actually get the time that was asked for.
end
else
if TimeOfDay > TimeToSet then
World:SetTimeOfDay(TimeOfDay + AnimationSpeed)
World:ScheduleTask(1, DoAnimation)
else
World:SetTimeOfDay(TimeToSet) -- Make sure we actually get the time that was asked for.
end
end
end
World:ScheduleTask(1, DoAnimation)
World:BroadcastChatSuccess("Time was set to " .. TimeToSet)
LOG("Time in world \"" .. World:GetName() .. "\" was set to " .. TimeToSet) -- Let the console know about time changes
return true
end
-- Code common to console and in-game `time add` command
local function CommonAddTime( World, Time )
-- Stop if an invalid world was given
if not World then
return true
end
local TimeToAdd = tonumber( Time )
if not TimeToAdd then
return false
end
local TimeToSet = World:GetTimeOfDay() + TimeToAdd
SetTime( World, TimeToSet )
return true
end
-- Handler for "/time add <amount> [world]" subcommand
function HandleAddTimeCommand( Split, Player )
if not CommonAddTime( GetWorld( Split[4], Player ), Split[3] ) then
SendMessage( Player, PlayerTimeAddCommandUsage )
end
return true
end
-- Handler for console command: time add <value> [WorldName]
function HandleConsoleAddTime(a_Split)
if not CommonAddTime( GetWorld( a_Split[4] ), a_Split[3] ) then
LOG(ConsoleAddTimeCommandUsage)
end
return true
end
-- Code common to console and in-game `time set` command
local function CommonSetTime( World, Time )
-- Stop if an invalid world was given
if not World then
return true
end
-- Handle the vanilla cases of /time set <day|night>, for compatibility
local TimeToSet = SpecialTimesTable[Time] or tonumber(Time)
if not TimeToSet then
return false
else
SetTime( World, TimeToSet )
end
return true
end
-- Handler for "/time set <value> [world]" subcommand
function HandleSetTimeCommand( Split, Player )
if not CommonSetTime( GetWorld( Split[4], Player ), Split[3] ) then
SendMessage( Player, PlayerTimeSetCommandUsage )
end
return true
end
-- Handler for console command: time set <day|night|value> [world]
function HandleConsoleSetTime(a_Split)
if not CommonSetTime( GetWorld( a_Split[4] ), a_Split[3] ) then
LOG(ConsoleSetTimeCommandUsage)
end
return true
end
-- Code common to console and in-game time <day|night> commands
local function CommonSpecialTime( World, TimeName )
-- Stop if an invalid world was given
if not World then
return true
end
SetTime( World, SpecialTimesTable[TimeName] )
return true
end
-- Handler for /time <day|night> [world]
function HandleSpecialTimeCommand( Split, Player )
return CommonSpecialTime( GetWorld( Split[3], Player ), Split[2] )
end
-- Handler for console command: time <day|night> [world]
function HandleConsoleSpecialTime(a_Split)
return CommonSpecialTime( GetWorld( a_Split[3] ), a_Split[2] )
end
-- Handler for /time query daytime [world]
function HandleQueryDaytimeCommand( Split, Player )
local World = GetWorld( Split[4], Player )
-- Stop if an invalid world was given
if not World then
return true
end
SendMessage( Player, "The current time in World \"" .. World:GetName() .. "\" is " .. World:GetTimeOfDay() )
return true
end
-- Handler for console command: time query daytime [world]
function HandleConsoleQueryDaytime(a_Split)
local World = GetWorld( a_Split[4] )
-- Stop if an invalid world was given
if not World then
return true
end
LOG( "The current time in World \"" .. World:GetName() .. "\" is " .. World:GetTimeOfDay() )
return true
end
-- Handler for /time query gametime [world]
function HandleQueryGametimeCommand( Split, Player )
local World = GetWorld( Split[4], Player )
-- Stop if an invalid world was given
if not World then
return true
end
SendMessage( Player, "The World \"" .. World:GetName() .. "\" has existed for " .. World:GetWorldAge() )
return true
end
-- Handler for console command: time query gametime [world]
function HandleConsoleQueryGametime(a_Split)
local World = GetWorld( a_Split[4] )
-- Stop if an invalid world was given
if not World then
return true
end
LOG( "The World \"" .. World:GetName() .. "\" has existed for " .. World:GetWorldAge() )
return true
end
| apache-2.0 |
matthewhesketh/mattata | plugins/newchat.lua | 2 | 2128 | --[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local newchat = {}
local mattata = require('mattata')
local redis = require('libs.redis')
local json = require('dkjson')
function newchat:init()
newchat.commands = mattata.commands(self.info.username):command('newchat').table
end
function newchat:on_message(message, configuration, language)
if not mattata.is_global_admin(message.from.id)
then
return false
end
local input = mattata.input(message.text)
if not input
then
return false
end
local link, title = input:match('^(.-) (.-)$')
if not title
then
link = input
title = link
end
if not link
then
return mattata.send_reply(
message,
'Please specify a link to add to the list shown when /groups is sent. You need to use the following syntax: /newchat <link> [title]. If a title isn\'t given, the link will be used as the title too.'
)
elseif not link:match('https?://t%.me/.-$')
then
return mattata.send_reply(
message,
'The link must begin with "https://t.me/"!'
)
end
local entry = json.encode(
{
['link'] = tostring(link),
['title'] = tostring(title)
}
)
local entries = redis:smembers('mattata:configuration:chats')
for k, v in pairs(entries)
do
if not v
or not json.decode(v).link
or not json.decode(v).title
then
return false
elseif json.decode(v).link == link
then
return mattata.send_reply(
message,
'That link already exists in the database, under the name "' .. json.decode(v).title .. '"!'
)
end
end
redis:sadd(
'mattata:configuration:chats',
entry
)
return mattata.send_reply(
message,
'I have added that link to the list shown when /groups is sent, under the name "' .. title .. '"!'
)
end
return newchat | mit |
czfshine/Don-t-Starve | data/scripts/prefabs/pigman.lua | 1 | 18133 | require "brains/pigbrain"
require "brains/pigguardbrain"
require "brains/werepigbrain"
require "stategraphs/SGpig"
require "stategraphs/SGwerepig"
local assets =
{
Asset("ANIM", "anim/ds_pig_basic.zip"),
Asset("ANIM", "anim/ds_pig_actions.zip"),
Asset("ANIM", "anim/ds_pig_attacks.zip"),
Asset("ANIM", "anim/pig_build.zip"),
Asset("ANIM", "anim/pigspotted_build.zip"),
Asset("ANIM", "anim/pig_guard_build.zip"),
Asset("ANIM", "anim/werepig_build.zip"),
Asset("ANIM", "anim/werepig_basic.zip"),
Asset("ANIM", "anim/werepig_actions.zip"),
Asset("SOUND", "sound/pig.fsb"),
}
local prefabs =
{
"meat",
"monstermeat",
"poop",
"tophat",
"strawhat",
"pigskin",
}
local MAX_TARGET_SHARES = 5
local SHARE_TARGET_DIST = 30
local function ontalk(inst, script)
inst.SoundEmitter:PlaySound("dontstarve/pig/grunt")
end
local function CalcSanityAura(inst, observer)
if inst.components.werebeast
and inst.components.werebeast:IsInWereState() then
return -TUNING.SANITYAURA_LARGE
end
if inst.components.follower and inst.components.follower.leader == observer then
return TUNING.SANITYAURA_SMALL
end
return 0
end
local function ShouldAcceptItem(inst, item)
if inst.components.sleeper:IsAsleep() then
return false
end
if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then
return true
end
if item.components.edible then
if (item.components.edible.foodtype == "MEAT" or item.components.edible.foodtype == "HORRIBLE")
and inst.components.follower.leader
and inst.components.follower:GetLoyaltyPercent() > 0.9 then
return false
end
if item.components.edible.foodtype == "VEGGIE" then
local last_eat_time = inst.components.eater:TimeSinceLastEating()
if last_eat_time and last_eat_time < TUNING.PIG_MIN_POOP_PERIOD then
return false
end
if inst.components.inventory:Has(item.prefab, 1) then
return false
end
end
return true
end
end
local function OnGetItemFromPlayer(inst, giver, item)
--I eat food
if item.components.edible then
--meat makes us friends (unless I'm a guard)
if item.components.edible.foodtype == "MEAT" or item.components.edible.foodtype == "HORRIBLE" then
if inst.components.combat.target and inst.components.combat.target == giver then
inst.components.combat:SetTarget(nil)
elseif giver.components.leader and not inst:HasTag("guard") then
inst.SoundEmitter:PlaySound("dontstarve/common/makeFriend")
giver.components.leader:AddFollower(inst)
inst.components.follower:AddLoyaltyTime(item.components.edible:GetHunger() * TUNING.PIG_LOYALTY_PER_HUNGER)
end
end
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
--I wear hats
if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then
local current = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
if current then
inst.components.inventory:DropItem(current)
end
inst.components.inventory:Equip(item)
inst.AnimState:Show("hat")
end
end
local function OnRefuseItem(inst, item)
inst.sg:GoToState("refuse")
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
local function OnEat(inst, food)
if food.components.edible
and food.components.edible.foodtype == "MEAT"
and inst.components.werebeast
and not inst.components.werebeast:IsInWereState() then
if food.components.edible:GetHealth() < 0 then
inst.components.werebeast:TriggerDelta(1)
end
end
if food.components.edible and food.components.edible.foodtype == "VEGGIE" then
local poo = SpawnPrefab("poop")
poo.Transform:SetPosition(inst.Transform:GetWorldPosition())
end
end
local function OnAttacked(inst, data)
--print(inst, "OnAttacked")
local attacker = data.attacker
inst.components.combat:SetTarget(attacker)
if inst:HasTag("werepig") then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("werepig") end, MAX_TARGET_SHARES)
elseif inst:HasTag("guard") then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("pig") and (dude:HasTag("guard") or not attacker:HasTag("pig")) end, MAX_TARGET_SHARES)
else
if not (attacker:HasTag("pig") and attacker:HasTag("guard") ) then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("pig") and not dude:HasTag("werepig") end, MAX_TARGET_SHARES)
end
end
end
local function OnNewTarget(inst, data)
if inst:HasTag("werepig") then
--print(inst, "OnNewTarget", data.target)
inst.components.combat:ShareTarget(data.target, SHARE_TARGET_DIST, function(dude) return dude:HasTag("werepig") end, MAX_TARGET_SHARES)
end
end
local builds = {"pig_build", "pigspotted_build"}
local guardbuilds = {"pig_guard_build"}
local function NormalRetargetFn(inst)
return FindEntity(inst, TUNING.PIG_TARGET_DIST,
function(guy)
if not guy.LightWatcher or guy.LightWatcher:IsInLight() then
return guy:HasTag("monster") and guy.components.health and not guy.components.health:IsDead() and inst.components.combat:CanTarget(guy) and not
(inst.components.follower.leader ~= nil and guy:HasTag("abigail"))
end
end)
end
local function NormalKeepTargetFn(inst, target)
--give up on dead guys, or guys in the dark, or werepigs
return inst.components.combat:CanTarget(target)
and (not target.LightWatcher or target.LightWatcher:IsInLight())
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function NormalShouldSleep(inst)
if inst.components.follower and inst.components.follower.leader then
local fire = FindEntity(inst, 6, function(ent)
return ent.components.burnable
and ent.components.burnable:IsBurning()
end, {"campfire"})
return DefaultSleepTest(inst) and fire and (not inst.LightWatcher or inst.LightWatcher:IsInLight())
else
return DefaultSleepTest(inst)
end
end
local function SetNormalPig(inst)
inst:RemoveTag("werepig")
inst:RemoveTag("guard")
local brain = require "brains/pigbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGpig")
inst.AnimState:SetBuild(inst.build)
inst.components.werebeast:SetOnNormalFn(SetNormalPig)
inst.components.sleeper:SetResistance(2)
inst.components.combat:SetDefaultDamage(TUNING.PIG_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.PIG_ATTACK_PERIOD)
inst.components.combat:SetKeepTargetFunction(NormalKeepTargetFn)
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(NormalShouldSleep)
inst.components.sleeper:SetWakeTest(DefaultWakeTest)
inst.components.lootdropper:SetLoot({})
inst.components.lootdropper:AddRandomLoot("meat",3)
inst.components.lootdropper:AddRandomLoot("pigskin",1)
inst.components.lootdropper.numrandomloot = 1
inst.components.health:SetMaxHealth(TUNING.PIG_HEALTH)
inst.components.combat:SetRetargetFunction(3, NormalRetargetFn)
inst.components.combat:SetTarget(nil)
inst.components.trader:Enable()
inst.components.talker:StopIgnoringAll()
inst.components.combat:SetHurtSound(nil)
end
local function GuardRetargetFn(inst)
local home = inst.components.homeseeker and inst.components.homeseeker.home
--defend the king, then the torch, then myself
local defenseTarget = FindEntity(inst, TUNING.PIG_GUARD_DEFEND_DIST, function(guy) return guy:HasTag("king") end)
if not defenseTarget and home and inst:GetDistanceSqToInst(home) < TUNING.PIG_GUARD_DEFEND_DIST*TUNING.PIG_GUARD_DEFEND_DIST then
defenseTarget = home
end
if not defenseTarget then
defenseTarget = inst
end
local invader = FindEntity(defenseTarget or inst, TUNING.PIG_GUARD_TARGET_DIST, function(guy)
return guy:HasTag("character") and not guy:HasTag("guard")
end)
if not defenseTarget.happy then
if invader
and not (defenseTarget.components.trader and defenseTarget.components.trader:IsTryingToTradeWithMe(invader) )
and not (inst.components.trader and inst.components.trader:IsTryingToTradeWithMe(invader) ) then
return invader
end
if not GetClock():IsDay() and home and home.components.burnable and home.components.burnable:IsBurning() then
local lightThief = FindEntity(home, home.components.burnable:GetLargestLightRadius(), function(guy)
return guy:HasTag("player")
and guy.LightWatcher:IsInLight()
and not (defenseTarget.components.trader and defenseTarget.components.trader:IsTryingToTradeWithMe(guy) )
and not (inst.components.trader and inst.components.trader:IsTryingToTradeWithMe(guy) )
end)
if lightThief then
return lightThief
end
end
end
return FindEntity(defenseTarget, TUNING.PIG_GUARD_DEFEND_DIST, function(guy)
return guy:HasTag("monster")
end)
end
local function GuardKeepTargetFn(inst, target)
local home = inst.components.homeseeker and inst.components.homeseeker.home
if home then
local defendDist = TUNING.PIG_GUARD_DEFEND_DIST
if not GetClock():IsDay() and home.components.burnable and home.components.burnable:IsBurning() then
defendDist = home.components.burnable:GetLargestLightRadius()
end
return home:GetDistanceSqToInst(target) < defendDist*defendDist
and home:GetDistanceSqToInst(inst) < defendDist*defendDist
end
return inst.components.combat:CanTarget(target)
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function GuardShouldSleep(inst)
return false
end
local function GuardShouldWake(inst)
return true
end
local function SetGuardPig(inst)
inst:RemoveTag("werepig")
inst:AddTag("guard")
local brain = require "brains/pigguardbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGpig")
inst.AnimState:SetBuild(inst.build)
inst.components.werebeast:SetOnNormalFn(SetGuardPig)
inst.components.sleeper:SetResistance(3)
inst.components.health:SetMaxHealth(TUNING.PIG_GUARD_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.PIG_GUARD_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.PIG_GUARD_ATTACK_PERIOD)
inst.components.combat:SetKeepTargetFunction(GuardKeepTargetFn)
inst.components.combat:SetRetargetFunction(1, GuardRetargetFn)
inst.components.combat:SetTarget(nil)
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(GuardShouldSleep)
inst.components.sleeper:SetWakeTest(GuardShouldWake)
inst.components.lootdropper:SetLoot({})
inst.components.lootdropper:AddRandomLoot("meat",3)
inst.components.lootdropper:AddRandomLoot("pigskin",1)
inst.components.lootdropper.numrandomloot = 1
inst.components.trader:Enable()
inst.components.talker:StopIgnoringAll()
inst.components.follower:SetLeader(nil)
inst.components.combat:SetHurtSound(nil)
end
local function WerepigRetargetFn(inst)
return FindEntity(inst, TUNING.PIG_TARGET_DIST, function(guy)
return inst.components.combat:CanTarget(guy)
and not guy:HasTag("werepig")
and not (guy.sg and guy.sg:HasStateTag("transform") )
and not guy:HasTag("alwaysblock")
end)
end
local function WerepigKeepTargetFn(inst, target)
return inst.components.combat:CanTarget(target)
and not target:HasTag("werepig")
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function WerepigSleepTest(inst)
return false
end
local function WerepigWakeTest(inst)
return true
end
local function SetWerePig(inst)
inst:AddTag("werepig")
inst:RemoveTag("guard")
local brain = require "brains/werepigbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGwerepig")
inst.AnimState:SetBuild("werepig_build")
inst.components.sleeper:SetResistance(3)
inst.components.combat:SetDefaultDamage(TUNING.WEREPIG_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.WEREPIG_ATTACK_PERIOD)
inst.components.locomotor.runspeed = TUNING.WEREPIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.WEREPIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(WerepigSleepTest)
inst.components.sleeper:SetWakeTest(WerepigWakeTest)
inst.components.lootdropper:SetLoot({"meat","meat", "pigskin"})
inst.components.lootdropper.numrandomloot = 0
inst.components.health:SetMaxHealth(TUNING.WEREPIG_HEALTH)
inst.components.combat:SetTarget(nil)
inst.components.combat:SetRetargetFunction(3, WerepigRetargetFn)
inst.components.combat:SetKeepTargetFunction(WerepigKeepTargetFn)
inst.components.trader:Disable()
inst.components.follower:SetLeader(nil)
inst.components.talker:IgnoreAll()
inst.components.combat:SetHurtSound("dontstarve/creatures/werepig/hurt")
end
local function common()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 1.5, .75 )
inst.Transform:SetFourFaced()
inst.entity:AddLightWatcher()
inst:AddComponent("talker")
inst.components.talker.ontalk = ontalk
inst.components.talker.fontsize = 35
inst.components.talker.font = TALKINGFONT
--inst.components.talker.colour = Vector3(133/255, 140/255, 167/255)
inst.components.talker.offset = Vector3(0,-400,0)
MakeCharacterPhysics(inst, 50, .5)
inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED --5
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED --3
inst:AddTag("character")
inst:AddTag("pig")
inst:AddTag("scarytoprey")
anim:SetBank("pigman")
anim:PlayAnimation("idle_loop")
anim:Hide("hat")
------------------------------------------
inst:AddComponent("eater")
inst.components.eater:SetOmnivore()
inst.components.eater:SetCanEatHorrible()
inst.components.eater.strongstomach = true -- can eat monster meat!
inst.components.eater:SetOnEatFn(OnEat)
------------------------------------------
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "pig_torso"
MakeMediumBurnableCharacter(inst, "pig_torso")
inst:AddComponent("named")
inst.components.named.possiblenames = STRINGS.PIGNAMES
inst.components.named:PickNewName()
------------------------------------------
inst:AddComponent("werebeast")
inst.components.werebeast:SetOnWereFn(SetWerePig)
inst.components.werebeast:SetTriggerLimit(4)
------------------------------------------
inst:AddComponent("follower")
inst.components.follower.maxfollowtime = TUNING.PIG_LOYALTY_MAXTIME
------------------------------------------
inst:AddComponent("health")
------------------------------------------
inst:AddComponent("inventory")
------------------------------------------
inst:AddComponent("lootdropper")
------------------------------------------
inst:AddComponent("knownlocations")
------------------------------------------
inst:AddComponent("trader")
inst.components.trader:SetAcceptTest(ShouldAcceptItem)
inst.components.trader.onaccept = OnGetItemFromPlayer
inst.components.trader.onrefuse = OnRefuseItem
------------------------------------------
inst:AddComponent("sanityaura")
inst.components.sanityaura.aurafn = CalcSanityAura
------------------------------------------
inst:AddComponent("sleeper")
------------------------------------------
MakeMediumFreezableCharacter(inst, "pig_torso")
------------------------------------------
inst:AddComponent("inspectable")
inst.components.inspectable.getstatus = function(inst)
if inst:HasTag("werepig") then
return "WEREPIG"
elseif inst:HasTag("guard") then
return "GUARD"
elseif inst.components.follower.leader ~= nil then
return "FOLLOWER"
end
end
------------------------------------------
inst.OnSave = function(inst, data)
data.build = inst.build
end
inst.OnLoad = function(inst, data)
if data then
inst.build = data.build or builds[1]
if not inst.components.werebeast:IsInWereState() then
inst.AnimState:SetBuild(inst.build)
end
end
end
inst:ListenForEvent("attacked", OnAttacked)
inst:ListenForEvent("newcombattarget", OnNewTarget)
return inst
end
local function normal()
local inst = common()
inst.build = builds[math.random(#builds)]
inst.AnimState:SetBuild(inst.build)
SetNormalPig(inst)
return inst
end
local function guard()
local inst = common()
inst.build = guardbuilds[math.random(#guardbuilds)]
inst.AnimState:SetBuild(inst.build)
SetGuardPig(inst)
return inst
end
return Prefab( "common/characters/pigman", normal, assets, prefabs),
Prefab("common/character/pigguard", guard, assets, prefabs)
| gpl-2.0 |
czfshine/Don-t-Starve | data/DLC0001/scripts/prefabs/pigman.lua | 1 | 20165 | require "brains/pigbrain"
require "brains/pigguardbrain"
require "brains/werepigbrain"
require "stategraphs/SGpig"
require "stategraphs/SGwerepig"
local assets =
{
Asset("ANIM", "anim/ds_pig_basic.zip"),
Asset("ANIM", "anim/ds_pig_actions.zip"),
Asset("ANIM", "anim/ds_pig_attacks.zip"),
Asset("ANIM", "anim/pig_build.zip"),
Asset("ANIM", "anim/pigspotted_build.zip"),
Asset("ANIM", "anim/pig_guard_build.zip"),
Asset("ANIM", "anim/werepig_build.zip"),
Asset("ANIM", "anim/werepig_basic.zip"),
Asset("ANIM", "anim/werepig_actions.zip"),
Asset("SOUND", "sound/pig.fsb"),
}
local prefabs =
{
"meat",
"monstermeat",
"poop",
"tophat",
"strawhat",
"pigskin",
}
local MAX_TARGET_SHARES = 5
local SHARE_TARGET_DIST = 30
local function ontalk(inst, script)
inst.SoundEmitter:PlaySound("dontstarve/pig/grunt")
end
local function SpringMod(amt)
if GetSeasonManager() and GetSeasonManager():IsSpring() then
return amt * TUNING.SPRING_COMBAT_MOD
else
return amt
end
end
local function CalcSanityAura(inst, observer)
if inst.components.werebeast
and inst.components.werebeast:IsInWereState() then
return -TUNING.SANITYAURA_LARGE
end
if inst.components.follower and inst.components.follower.leader == observer then
return TUNING.SANITYAURA_SMALL
end
return 0
end
local function ShouldAcceptItem(inst, item)
if inst.components.sleeper:IsAsleep() then
return false
end
if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then
return true
end
if item.components.edible then
if (item.components.edible.foodtype == "MEAT" or item.components.edible.foodtype == "HORRIBLE")
and inst.components.follower.leader
and inst.components.follower:GetLoyaltyPercent() > 0.9 then
return false
end
if (item.components.edible.foodtype == "VEGGIE" or item.components.edible.foodtype == "RAW") then
local last_eat_time = inst.components.eater:TimeSinceLastEating()
if last_eat_time and last_eat_time < TUNING.PIG_MIN_POOP_PERIOD then
return false
end
if inst.components.inventory:Has(item.prefab, 1) then
return false
end
end
return true
end
end
local function OnGetItemFromPlayer(inst, giver, item)
--I eat food
if item.components.edible then
--meat makes us friends (unless I'm a guard)
if item.components.edible.foodtype == "MEAT" or item.components.edible.foodtype == "HORRIBLE" then
if inst.components.combat.target and inst.components.combat.target == giver then
inst.components.combat:SetTarget(nil)
elseif giver.components.leader and not inst:HasTag("guard") then
inst.SoundEmitter:PlaySound("dontstarve/common/makeFriend")
giver.components.leader:AddFollower(inst)
inst.components.follower:AddLoyaltyTime(item.components.edible:GetHunger() * TUNING.PIG_LOYALTY_PER_HUNGER)
end
end
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
--I wear hats
if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then
local current = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
if current then
inst.components.inventory:DropItem(current)
end
inst.components.inventory:Equip(item)
inst.AnimState:Show("hat")
end
end
local function OnRefuseItem(inst, item)
inst.sg:GoToState("refuse")
if inst.components.sleeper:IsAsleep() then
inst.components.sleeper:WakeUp()
end
end
local function OnEat(inst, food)
if food.components.edible
and food.components.edible.foodtype == "MEAT"
and inst.components.werebeast
and not inst.components.werebeast:IsInWereState() then
if food.components.edible:GetHealth() < 0 then
inst.components.werebeast:TriggerDelta(1)
end
end
if food.components.edible and food.components.edible.foodtype == "VEGGIE" then
local poo = SpawnPrefab("poop")
poo.Transform:SetPosition(inst.Transform:GetWorldPosition())
end
end
local function OnAttackedByDecidRoot(inst, attacker)
local fn = function(dude) return dude:HasTag("pig") and not dude:HasTag("werepig") and not dude:HasTag("guard") end
local x,y,z = inst.Transform:GetWorldPosition()
local ents = nil
if GetSeasonManager() and GetSeasonManager():IsSpring() then
ents = TheSim:FindEntities(x,y,z, (SHARE_TARGET_DIST * TUNING.SPRING_COMBAT_MOD) / 2)
else
ents = TheSim:FindEntities(x,y,z, SHARE_TARGET_DIST / 2)
end
if ents then
local num_helpers = 0
for k,v in pairs(ents) do
if v ~= inst and v.components.combat and not (v.components.health and v.components.health:IsDead()) and fn(v) then
if v:PushEvent("suggest_tree_target", {tree=attacker}) then
num_helpers = num_helpers + 1
end
end
if num_helpers >= MAX_TARGET_SHARES then
break
end
end
end
end
local function OnAttacked(inst, data)
--print(inst, "OnAttacked")
local attacker = data.attacker
inst:ClearBufferedAction()
if attacker.prefab == "deciduous_root" and attacker.owner then
OnAttackedByDecidRoot(inst, attacker.owner)
elseif attacker.prefab ~= "deciduous_root" then
inst.components.combat:SetTarget(attacker)
if inst:HasTag("werepig") then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("werepig") end, MAX_TARGET_SHARES)
elseif inst:HasTag("guard") then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("pig") and (dude:HasTag("guard") or not attacker:HasTag("pig")) end, MAX_TARGET_SHARES)
else
if not (attacker:HasTag("pig") and attacker:HasTag("guard") ) then
inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("pig") and not dude:HasTag("werepig") end, MAX_TARGET_SHARES)
end
end
end
end
local function OnNewTarget(inst, data)
if inst:HasTag("werepig") then
--print(inst, "OnNewTarget", data.target)
inst.components.combat:ShareTarget(data.target, SHARE_TARGET_DIST, function(dude) return dude:HasTag("werepig") end, MAX_TARGET_SHARES)
end
end
local builds = {"pig_build", "pigspotted_build"}
local guardbuilds = {"pig_guard_build"}
local function NormalRetargetFn(inst)
return FindEntity(inst, TUNING.PIG_TARGET_DIST,
function(guy)
if not guy.LightWatcher or guy.LightWatcher:IsInLight() then
return guy:HasTag("monster") and guy.components.health and not guy.components.health:IsDead() and inst.components.combat:CanTarget(guy) and not
(inst.components.follower.leader ~= nil and guy:HasTag("abigail"))
end
end)
end
local function NormalKeepTargetFn(inst, target)
--give up on dead guys, or guys in the dark, or werepigs
return inst.components.combat:CanTarget(target)
and (not target.LightWatcher or target.LightWatcher:IsInLight())
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function NormalShouldSleep(inst)
if inst.components.follower and inst.components.follower.leader then
local fire = FindEntity(inst, 6, function(ent)
return ent.components.burnable
and ent.components.burnable:IsBurning()
end, {"campfire"})
return DefaultSleepTest(inst) and fire and (not inst.LightWatcher or inst.LightWatcher:IsInLight())
else
return DefaultSleepTest(inst)
end
end
local function SetNormalPig(inst)
inst:RemoveTag("werepig")
inst:RemoveTag("guard")
local brain = require "brains/pigbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGpig")
inst.AnimState:SetBuild(inst.build)
inst.components.werebeast:SetOnNormalFn(SetNormalPig)
inst.components.sleeper:SetResistance(2)
inst.components.combat:SetDefaultDamage(TUNING.PIG_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.PIG_ATTACK_PERIOD)
inst.components.combat:SetKeepTargetFunction(NormalKeepTargetFn)
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(NormalShouldSleep)
inst.components.sleeper:SetWakeTest(DefaultWakeTest)
inst.components.lootdropper:SetLoot({})
inst.components.lootdropper:AddRandomLoot("meat",3)
inst.components.lootdropper:AddRandomLoot("pigskin",1)
inst.components.lootdropper.numrandomloot = 1
inst.components.health:SetMaxHealth(TUNING.PIG_HEALTH)
inst.components.combat:SetRetargetFunction(3, NormalRetargetFn)
inst.components.combat:SetTarget(nil)
inst:ListenForEvent("suggest_tree_target", function(inst, data)
if data and data.tree and inst:GetBufferedAction() ~= ACTIONS.CHOP then
inst.tree_target = data.tree
end
end)
inst.components.trader:Enable()
inst.components.talker:StopIgnoringAll()
end
local function GuardRetargetFn(inst)
local home = inst.components.homeseeker and inst.components.homeseeker.home
--defend the king, then the torch, then myself
local defenseTarget = FindEntity(inst, TUNING.PIG_GUARD_DEFEND_DIST, function(guy) return guy:HasTag("king") end)
if not defenseTarget and home and inst:GetDistanceSqToInst(home) < SpringMod(TUNING.PIG_GUARD_DEFEND_DIST*TUNING.PIG_GUARD_DEFEND_DIST) then
defenseTarget = home
end
if not defenseTarget then
defenseTarget = inst
end
local invader = FindEntity(defenseTarget or inst, SpringMod(TUNING.PIG_GUARD_TARGET_DIST), function(guy)
return guy:HasTag("character") and not guy:HasTag("guard")
end)
if not defenseTarget.happy then
if invader
and not (defenseTarget.components.trader and defenseTarget.components.trader:IsTryingToTradeWithMe(invader) )
and not (inst.components.trader and inst.components.trader:IsTryingToTradeWithMe(invader) ) then
return invader
end
if not GetClock():IsDay() and home and home.components.burnable and home.components.burnable:IsBurning() then
local lightThief = FindEntity(home, home.components.burnable:GetLargestLightRadius(), function(guy)
return guy:HasTag("player")
and guy.LightWatcher:IsInLight()
and not (defenseTarget.components.trader and defenseTarget.components.trader:IsTryingToTradeWithMe(guy) )
and not (inst.components.trader and inst.components.trader:IsTryingToTradeWithMe(guy) )
end)
if lightThief then
return lightThief
end
end
end
return FindEntity(defenseTarget, SpringMod(TUNING.PIG_GUARD_DEFEND_DIST), function(guy)
return guy:HasTag("monster")
end)
end
local function GuardKeepTargetFn(inst, target)
local home = inst.components.homeseeker and inst.components.homeseeker.home
if home then
local defendDist = SpringMod(TUNING.PIG_GUARD_DEFEND_DIST)
if not GetClock():IsDay() and home.components.burnable and home.components.burnable:IsBurning() then
defendDist = home.components.burnable:GetLargestLightRadius()
end
return home:GetDistanceSqToInst(target) < defendDist*defendDist
and home:GetDistanceSqToInst(inst) < defendDist*defendDist
end
return inst.components.combat:CanTarget(target)
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function GuardShouldSleep(inst)
return false
end
local function GuardShouldWake(inst)
return true
end
local function SetGuardPig(inst)
inst:RemoveTag("werepig")
inst:AddTag("guard")
local brain = require "brains/pigguardbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGpig")
inst.AnimState:SetBuild(inst.build)
inst.components.werebeast:SetOnNormalFn(SetGuardPig)
inst.components.sleeper:SetResistance(3)
inst.components.health:SetMaxHealth(TUNING.PIG_GUARD_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.PIG_GUARD_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.PIG_GUARD_ATTACK_PERIOD)
inst.components.combat:SetKeepTargetFunction(GuardKeepTargetFn)
inst.components.combat:SetRetargetFunction(1, GuardRetargetFn)
inst.components.combat:SetTarget(nil)
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(GuardShouldSleep)
inst.components.sleeper:SetWakeTest(GuardShouldWake)
inst.components.lootdropper:SetLoot({})
inst.components.lootdropper:AddRandomLoot("meat",3)
inst.components.lootdropper:AddRandomLoot("pigskin",1)
inst.components.lootdropper.numrandomloot = 1
inst.components.trader:Enable()
inst.components.talker:StopIgnoringAll()
inst.components.follower:SetLeader(nil)
end
local function WerepigRetargetFn(inst)
return FindEntity(inst, SpringMod(TUNING.PIG_TARGET_DIST), function(guy)
return inst.components.combat:CanTarget(guy)
and not guy:HasTag("werepig")
and not (guy.sg and guy.sg:HasStateTag("transform") )
and not guy:HasTag("alwaysblock")
end)
end
local function WerepigKeepTargetFn(inst, target)
return inst.components.combat:CanTarget(target)
and not target:HasTag("werepig")
and not (target.sg and target.sg:HasStateTag("transform") )
end
local function WerepigSleepTest(inst)
return false
end
local function WerepigWakeTest(inst)
return true
end
local function SetWerePig(inst)
inst:AddTag("werepig")
inst:RemoveTag("guard")
local brain = require "brains/werepigbrain"
inst:SetBrain(brain)
inst:SetStateGraph("SGwerepig")
inst.AnimState:SetBuild("werepig_build")
inst.components.sleeper:SetResistance(3)
inst.components.combat:SetDefaultDamage(TUNING.WEREPIG_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.WEREPIG_ATTACK_PERIOD)
inst.components.locomotor.runspeed = TUNING.WEREPIG_RUN_SPEED
inst.components.locomotor.walkspeed = TUNING.WEREPIG_WALK_SPEED
inst.components.sleeper:SetSleepTest(WerepigSleepTest)
inst.components.sleeper:SetWakeTest(WerepigWakeTest)
inst.components.lootdropper:SetLoot({"meat","meat", "pigskin"})
inst.components.lootdropper.numrandomloot = 0
inst.components.health:SetMaxHealth(TUNING.WEREPIG_HEALTH)
inst.components.combat:SetTarget(nil)
inst.components.combat:SetRetargetFunction(3, WerepigRetargetFn)
inst.components.combat:SetKeepTargetFunction(WerepigKeepTargetFn)
inst.components.trader:Disable()
inst.components.follower:SetLeader(nil)
inst.components.talker:IgnoreAll()
end
local function common()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 1.5, .75 )
inst.Transform:SetFourFaced()
inst.entity:AddLightWatcher()
inst:AddComponent("talker")
inst.components.talker.ontalk = ontalk
inst.components.talker.fontsize = 35
inst.components.talker.font = TALKINGFONT
--inst.components.talker.colour = Vector3(133/255, 140/255, 167/255)
inst.components.talker.offset = Vector3(0,-400,0)
MakeCharacterPhysics(inst, 50, .5)
inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED --5
inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED --3
inst:AddTag("character")
inst:AddTag("pig")
inst:AddTag("scarytoprey")
anim:SetBank("pigman")
anim:PlayAnimation("idle_loop")
anim:Hide("hat")
------------------------------------------
inst:AddComponent("eater")
inst.components.eater:SetOmnivore()
inst.components.eater:SetCanEatHorrible()
table.insert(inst.components.eater.foodprefs, "RAW")
table.insert(inst.components.eater.ablefoods, "RAW")
inst.components.eater.strongstomach = true -- can eat monster meat!
inst.components.eater:SetOnEatFn(OnEat)
------------------------------------------
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "pig_torso"
MakeMediumBurnableCharacter(inst, "pig_torso")
inst:AddComponent("named")
inst.components.named.possiblenames = STRINGS.PIGNAMES
inst.components.named:PickNewName()
------------------------------------------
inst:AddComponent("werebeast")
inst.components.werebeast:SetOnWereFn(SetWerePig)
inst.components.werebeast:SetTriggerLimit(4)
inst:ListenForEvent("exitlimbo", function(inst)
inst:DoTaskInTime(.2, function(inst)
if GetClock() and GetClock():GetMoonPhase() == "full" and GetClock():IsNight() and inst.entity:IsVisible() and not inst.components.werebeast:IsInWereState() then
inst.components.werebeast:SetWere()
end
end)
end)
------------------------------------------
inst:AddComponent("follower")
inst.components.follower.maxfollowtime = TUNING.PIG_LOYALTY_MAXTIME
------------------------------------------
inst:AddComponent("health")
------------------------------------------
inst:AddComponent("inventory")
------------------------------------------
inst:AddComponent("lootdropper")
------------------------------------------
inst:AddComponent("knownlocations")
------------------------------------------
inst:AddComponent("trader")
inst.components.trader:SetAcceptTest(ShouldAcceptItem)
inst.components.trader.onaccept = OnGetItemFromPlayer
inst.components.trader.onrefuse = OnRefuseItem
------------------------------------------
inst:AddComponent("sanityaura")
inst.components.sanityaura.aurafn = CalcSanityAura
------------------------------------------
inst:AddComponent("sleeper")
------------------------------------------
MakeMediumFreezableCharacter(inst, "pig_torso")
------------------------------------------
inst:AddComponent("inspectable")
inst.components.inspectable.getstatus = function(inst)
if inst:HasTag("werepig") then
return "WEREPIG"
elseif inst:HasTag("guard") then
return "GUARD"
elseif inst.components.follower.leader ~= nil then
return "FOLLOWER"
end
end
------------------------------------------
inst.OnSave = function(inst, data)
data.build = inst.build
end
inst.OnLoad = function(inst, data)
if data then
inst.build = data.build or builds[1]
if not inst.components.werebeast:IsInWereState() then
inst.AnimState:SetBuild(inst.build)
end
end
end
inst:ListenForEvent("attacked", OnAttacked)
inst:ListenForEvent("newcombattarget", OnNewTarget)
return inst
end
local function normal()
local inst = common()
inst.build = builds[math.random(#builds)]
inst.AnimState:SetBuild(inst.build)
SetNormalPig(inst)
return inst
end
local function guard()
local inst = common()
inst.build = guardbuilds[math.random(#guardbuilds)]
inst.AnimState:SetBuild(inst.build)
SetGuardPig(inst)
return inst
end
return Prefab( "common/characters/pigman", normal, assets, prefabs),
Prefab("common/character/pigguard", guard, assets, prefabs)
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Gadgets/cmd_factory_stop_production.lua | 4 | 2841 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Factory Stop Production",
desc = "Adds a command to clear the factory queue",
author = "GoogleFrog",
date = "13 November 2016",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return false -- no unsynced code
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local cmdOpts = CMD.OPT_CTRL
include("LuaRules/Configs/customcmds.h.lua")
local isFactory = {}
for udid = 1, #UnitDefs do
local ud = UnitDefs[udid]
if ud.isFactory and not ud.customParams.notreallyafactory then
isFactory[udid] = true
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local stopProductionCmdDesc = {
id = CMD_STOP_PRODUCTION,
type = CMDTYPE.ICON,
name = 'Stop Production',
action = 'stopproduction',
cursor = 'Stop', -- Probably does nothing
tooltip = 'Clear the unit production queue.',
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Handle the command
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_STOP_PRODUCTION] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return isFactory
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if (cmdID ~= CMD_STOP_PRODUCTION) or (not isFactory[unitDefID]) then
return
end
local commands = Spring.GetFactoryCommands(unitID)
if not commands then
return
end
for i = 1, #commands do
Spring.GiveOrderToUnit(unitID, CMD.REMOVE, {commands[i].tag}, cmdOpts)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Add the command to factories
function gadget:UnitCreated(unitID, unitDefID)
if isFactory[unitDefID] then
spInsertUnitCmdDesc(unitID, stopProductionCmdDesc)
end
end
function gadget:Initialize()
gadgetHandler:RegisterCMDID(CMD_STOP_PRODUCTION)
for _, unitID in pairs(Spring.GetAllUnits()) do
gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID))
end
end
| gpl-2.0 |
czfshine/Don-t-Starve | ZeroBraneStudio/api/lua/moai.lua | 2 | 622957 | -- Documentation for Moai SDK 1.5 revision 1 (interim version by MoaiEdition) (http://getmoai.com/)
-- Generated on 2014-04-01 by DocExport v2.1.
-- DocExport is part of MoaiUtils (https://github.com/DanielSWolf/MoaiUtils).
return {
b2ContactListener = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
b2DestructionListener = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIAction = {
type = "class",
inherits = "MOAIBlocker MOAIInstanceEventSource",
description = "Base class for actions.",
childs = {
EVENT_STOP = {
type = "value",
description = "ID of event stop callback. Signature is: nil onStop ()"
},
addChild = {
type = "method",
description = "Attaches a child action for updating.\n\n–> MOAIAction self\n–> MOAIAction child\n<– MOAIAction self",
args = "(MOAIAction self, MOAIAction child)",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
attach = {
type = "method",
description = "Attaches a child to a parent action. The child will receive updates from the parent only if the parent is in the action tree.\n\n–> MOAIAction self\n[–> MOAIAction parent: Default value is nil; same effect as calling detach ().]\n<– MOAIAction self",
args = "(MOAIAction self, [MOAIAction parent])",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
clear = {
type = "method",
description = "Removes all child actions.\n\n–> MOAIAction self\n<– MOAIAction self",
args = "MOAIAction self",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
detach = {
type = "method",
description = "Detaches an action from its parent (if any) thereby removing it from the action tree. Same effect as calling stop ().\n\n–> MOAIAction self\n<– MOAIAction self",
args = "MOAIAction self",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
isActive = {
type = "method",
description = "Checks to see if an action is currently in the action tree.\n\n–> MOAIAction self\n<– boolean isActive",
args = "MOAIAction self",
returns = "boolean isActive",
valuetype = "boolean"
},
isBusy = {
type = "method",
description = "Checks to see if an action is currently busy. An action is 'busy' only if it is 'active' and not 'done.'\n\n–> MOAIAction self\n<– boolean isBusy",
args = "MOAIAction self",
returns = "boolean isBusy",
valuetype = "boolean"
},
isDone = {
type = "method",
description = "Checks to see if an action is 'done.' Definition of 'done' is up to individual action implementations.\n\n–> MOAIAction self\n<– boolean isDone",
args = "MOAIAction self",
returns = "boolean isDone",
valuetype = "boolean"
},
pause = {
type = "method",
description = "Leaves the action in the action tree but prevents it from receiving updates. Call pause ( false ) or start () to unpause.\n\n–> MOAIAction self\n[–> boolean pause: Default value is 'true.']\n<– nil",
args = "(MOAIAction self, [boolean pause])",
returns = "nil"
},
start = {
type = "method",
description = "Adds the action to a parent action or the root of the action tree.\n\n–> MOAIAction self\n[–> MOAIAction parent: Default value is MOAIActionMgr.getRoot ()]\n<– MOAIAction self",
args = "(MOAIAction self, [MOAIAction parent])",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
stop = {
type = "method",
description = "Removed the action from its parent action; action will stop being updated.\n\n–> MOAIAction self\n<– MOAIAction self",
args = "MOAIAction self",
returns = "MOAIAction self",
valuetype = "MOAIAction"
},
throttle = {
type = "method",
description = "Sets the actions throttle. Throttle is a scalar on time. Is is passed to the action's children.\n\n–> MOAIAction self\n[–> number throttle: Default value is 1.]\n<– MOAIAction self",
args = "(MOAIAction self, [number throttle])",
returns = "MOAIAction self",
valuetype = "MOAIAction"
}
}
},
MOAIActionMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "Manager class for MOAIActions.",
childs = {
getRoot = {
type = "function",
description = "Returns the current root action.\n\n<– MOAIAction root",
args = "()",
returns = "MOAIAction root",
valuetype = "MOAIAction"
},
setProfilingEnabled = {
type = "function",
description = "Enables action profiling.\n\n[–> boolean enable: Default value is false.]\n<– nil",
args = "[boolean enable]",
returns = "nil"
},
setRoot = {
type = "function",
description = "Replaces or clears the root action.\n\n[–> MOAIAction root: Default value is nil.]\n<– nil",
args = "[MOAIAction root]",
returns = "nil"
},
setThreadInfoEnabled = {
type = "function",
description = "Enables function name and line number info for MOAICoroutine.\n\n[–> boolean enable: Default value is false.]\n<– nil",
args = "[boolean enable]",
returns = "nil"
}
}
},
MOAIAdColonyAndroid = {
type = "class",
inherits = "MOAILuaObject",
childs = {
getDeviceID = {
type = "function",
description = "Request a unique ID for the device.\n\n<– string id: The device ID.",
args = "()",
returns = "string id",
valuetype = "string"
},
init = {
type = "function",
description = "Initialize AdColony.\n\n–> string appId: Available in AdColony dashboard settings.\n–> table zones: A list of zones to configure. Available in AdColony dashboard settings.\n<– nil",
args = "(string appId, table zones)",
returns = "nil"
},
playVideo = {
type = "function",
description = "Play an AdColony video ad.\n\n–> string zone: The zone from which to play a video ad.\n[–> boolean prompt: Determines whether the user is asked whether they want to play a video ad or not. Default is true.]\n[–> boolean confirm: Determines whether the user is presented with a confirmation dialog after video ad playback completes. Default is true.]\n<– nil",
args = "(string zone, [boolean prompt, [boolean confirm]])",
returns = "nil"
},
videoReadyForZone = {
type = "function",
description = "Check the readiness of a video ad for a given zone.\n\n–> string zone: The zone from which to check for a video ad.\n<– boolean isReady: True, if a video ad is ready to play.",
args = "string zone",
returns = "boolean isReady",
valuetype = "boolean"
}
}
},
MOAIAnim = {
type = "class",
inherits = "MOAITimer",
description = "Bind animation curves to nodes and provides timer controls for animation playback.",
childs = {
apply = {
type = "method",
description = "Apply the animation at a given time or time step.\n\nOverload:\n–> MOAIAnim self\n[–> number t0: Default value is 0.]\n<– nil\n\nOverload:\n–> MOAIAnim self\n–> number t0\n–> number t1\n<– nil",
args = "(MOAIAnim self, [number t0, [number t1]])",
returns = "nil"
},
getLength = {
type = "method",
description = "Return the length of the animation.\n\n–> MOAIAnim self\n<– number length",
args = "MOAIAnim self",
returns = "number length",
valuetype = "number"
},
reserveLinks = {
type = "method",
description = "Reserves a specified number of links for the animation.\n\n–> MOAIAnim self\n–> number nLinks\n<– nil",
args = "(MOAIAnim self, number nLinks)",
returns = "nil"
},
setLink = {
type = "method",
description = "Connect a curve to a given node attribute.\n\n–> MOAIAnim self\n–> number linkID\n–> MOAIAnimCurveBase curve\n–> MOAINode target: Target node.\n–> number attrID: Attribute of the target node to be driven by the curve.\n[–> boolean asDelta: 'true' to apply the curve as a delta instead of an absolute. Default value is false.]\n<– nil",
args = "(MOAIAnim self, number linkID, MOAIAnimCurveBase curve, MOAINode target, number attrID, [boolean asDelta])",
returns = "nil"
}
}
},
MOAIAnimCurve = {
type = "class",
inherits = "MOAIAnimCurveBase",
description = "Implementation of animation curve for floating point values.",
childs = {
getValueAtTime = {
type = "method",
description = "Return the interpolated value given a point in time along the curve. This does not change the curve's built in TIME attribute (it simply performs the requisite computation on demand).\n\n–> MOAIAnimCurve self\n–> number time\n<– number value: The interpolated value",
args = "(MOAIAnimCurve self, number time)",
returns = "number value",
valuetype = "number"
},
setKey = {
type = "method",
description = "Initialize a key frame at a given time with a give value. Also set the transition type between the specified key frame and the next key frame.\n\n–> MOAIAnimCurve self\n–> number index: Index of the keyframe.\n–> number time: Location of the key frame along the curve.\n–> number value: Value of the curve at time.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n[–> number weight: Blends between chosen ease type (of any) and a linear transition. Defaults to 1.]\n<– nil",
args = "(MOAIAnimCurve self, number index, number time, number value, [number mode, [number weight]])",
returns = "nil"
}
}
},
MOAIAnimCurveBase = {
type = "class",
inherits = "MOAINode",
description = "Piecewise animation function with one input (time) and one output (value). This is the base class for typed animation curves (float, quaternion, etc.).",
childs = {
APPEND = {
type = "value"
},
ATTR_TIME = {
type = "value"
},
ATTR_VALUE = {
type = "value"
},
CLAMP = {
type = "value"
},
MIRROR = {
type = "value"
},
WRAP = {
type = "value"
},
getLength = {
type = "method",
description = "Return the largest key frame time value in the curve.\n\n–> MOAIAnimCurveBase self\n<– number length",
args = "MOAIAnimCurveBase self",
returns = "number length",
valuetype = "number"
},
reserveKeys = {
type = "method",
description = "Reserve key frames.\n\n–> MOAIAnimCurveBase self\n–> number nKeys\n<– nil",
args = "(MOAIAnimCurveBase self, number nKeys)",
returns = "nil"
},
setWrapMode = {
type = "method",
description = "Sets the wrap mode for values above 1.0 and below 0.0. CLAMP sets all values above and below 1.0 and 0.0 to values at 1.0 and 0.0 respectively\n\n–> MOAIAnimCurveBase self\n[–> number mode: One of MOAIAnimCurveBase.CLAMP, MOAIAnimCurveBase.WRAP, MOAIAnimCurveBase.MIRROR, MOAIAnimCurveBase.APPEND. Default value is MOAIAnimCurveBase.CLAMP.]\n<– nil",
args = "(MOAIAnimCurveBase self, [number mode])",
returns = "nil"
}
}
},
MOAIAnimCurveQuat = {
type = "class",
inherits = "MOAIAnimCurveBase",
description = "Implementation of animation curve for rotation (via quaternion) values.",
childs = {
getValueAtTime = {
type = "method",
description = "Return the interpolated value (as Euler angles) given a point in time along the curve. This does not change the curve's built in TIME attribute (it simply performs the requisite computation on demand).\n\n–> MOAIAnimCurveQuat self\n–> number time\n<– number xRot\n<– number yRot\n<– number zRot",
args = "(MOAIAnimCurveQuat self, number time)",
returns = "(number xRot, number yRot, number zRot)",
valuetype = "number"
},
setKey = {
type = "method",
description = "Initialize a key frame at a given time with a give value (as Euler angles). Also set the transition type between the specified key frame and the next key frame.\n\n–> MOAIAnimCurveQuat self\n–> number index: Index of the keyframe.\n–> number time: Location of the key frame along the curve.\n–> number xRot: X rotation at time.\n–> number yRot: Y rotation at time.\n–> number zRot: Z rotation at time.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n[–> number weight: Blends between chosen ease type (of any) and a linear transition. Defaults to 1.]\n<– nil",
args = "(MOAIAnimCurveQuat self, number index, number time, number xRot, number yRot, number zRot, [number mode, [number weight]])",
returns = "nil"
}
}
},
MOAIAnimCurveVec = {
type = "class",
inherits = "MOAIAnimCurveBase",
description = "Implementation of animation curve for 3D vector values.",
childs = {
getValueAtTime = {
type = "method",
description = "Return the interpolated vector components given a point in time along the curve. This does not change the curve's built in TIME attribute (it simply performs the requisite computation on demand).\n\n–> MOAIAnimCurveVec self\n–> number time\n<– number x\n<– number y\n<– number z",
args = "(MOAIAnimCurveVec self, number time)",
returns = "(number x, number y, number z)",
valuetype = "number"
},
setKey = {
type = "method",
description = "Initialize a key frame at a given time with a give vector. Also set the transition type between the specified key frame and the next key frame.\n\n–> MOAIAnimCurveVec self\n–> number index: Index of the keyframe.\n–> number time: Location of the key frame along the curve.\n–> number x: X component at time.\n–> number y: Y component at time.\n–> number z: Z component at time.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n[–> number weight: Blends between chosen ease type (of any) and a linear transition. Defaults to 1.]\n<– nil",
args = "(MOAIAnimCurveVec self, number index, number time, number x, number y, number z, [number mode, [number weight]])",
returns = "nil"
}
}
},
MOAIApp = {
type = "class",
inherits = "MOAILuaObject",
childs = {
alert = {
type = "function",
description = "Display a modal style dialog box with one or more buttons, including a cancel button. This will not halt execution (this function returns immediately), so if you need to respond to the user's selection, pass a callback.\n\n–> string title: The title of the dialog box.\n–> string message: The message to display.\n–> function callback: The function that will receive an integer index as which button was pressed.\n–> string cancelTitle: The title of the cancel button.\n–> string... buttons: Other buttons to add to the alert box.\n<– nil",
args = "(string title, string message, function callback, string cancelTitle, string... buttons)",
returns = "nil"
},
canMakePayments = {
type = "function",
description = "Verify that the app has permission to request payments.\n\n<– boolean canMakePayments",
args = "()",
returns = "boolean canMakePayments",
valuetype = "boolean"
},
getDirectoryInDomain = {
type = "function",
description = "Search the platform's internal directory structure for a special directory as defined by the platform.\n\n–> number domain: One of MOAIApp.DOMAIN_DOCUMENTS, MOAIApp.DOMAIN_APP_SUPPORT\n<– string directory: The directory associated with the given domain.",
args = "number domain",
returns = "string directory",
valuetype = "string"
},
requestPaymentForProduct = {
type = "function",
description = "Request payment for a product.\n\n–> string productIdentifier\n[–> number quantity: Default value is 1.]\n<– nil",
args = "(string productIdentifier, [number quantity])",
returns = "nil"
},
requestProductIdentifiers = {
type = "function",
description = "Verify the validity of a set of products.\n\n–> table productIdentifiers: A table of product identifiers.\n<– nil",
args = "table productIdentifiers",
returns = "nil"
},
restoreCompletedTransactions = {
type = "function",
description = "Request a restore of all purchased non-consumables from the App Store. Use this to retrieve a list of all previously purchased items (for example after reinstalling the app on a different device).\n\n<– nil",
args = "()",
returns = "nil"
},
setListener = {
type = "function",
description = "Set a callback to handle events of a type.\n\n–> number event: One of MOAIApp.ERROR, MOAIApp.DID_REGISTER, MOAIApp.REMOTE_NOTIFICATION, MOAIApp.PAYMENT_QUEUE_TRANSACTION, MOAIApp.PRODUCT_REQUEST_RESPONSE.\n[–> function handler]\n<– nil",
args = "(number event, [function handler])",
returns = "nil"
}
}
},
MOAIAppAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for base application class on Android devices. Exposed to Lua via MOAIApp on all mobile platforms.",
childs = {
BACK_BUTTON_PRESSED = {
type = "value",
description = "Event code indicating that the physical device back button was pressed."
},
SESSION_END = {
type = "value",
description = "Event code indicating the end of an app sessions."
},
SESSION_START = {
type = "value",
description = "Event code indicating the beginning of an app session."
},
getStatusBarHeight = {
type = "function",
description = "Gets the Height of an Android 3.x status bar\n\n<– number height",
args = "()",
returns = "number height",
valuetype = "number"
},
getUTCTime = {
type = "function",
description = "Gets the UTC time.\n\n<– number time: UTC Time",
args = "()",
returns = "number time",
valuetype = "number"
},
sendMail = {
type = "function",
description = "Send a mail with the passed in default values\n\n–> string recipient\n–> string subject\n–> string message\n<– nil",
args = "(string recipient, string subject, string message)",
returns = "nil"
},
share = {
type = "function",
description = "Open a generic Android dialog to allow the user to share via email, SMS, Facebook, Twitter, etc.\n\n–> string prompt: The prompt to show the user.\n–> string subject: The subject of the message to share.\n–> string text: The text of the message to share.\n<– nil",
args = "(string prompt, string subject, string text)",
returns = "nil"
}
}
},
MOAIAppIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for base application class on iOS devices. Exposed to Lua via MOAIApp on all mobile platforms.",
childs = {
APP_OPENED_FROM_URL = {
type = "value",
description = "Event code indicating that the app was stared via a URL click."
},
DOMAIN_APP_SUPPORT = {
type = "value",
description = "Directory domain 'application support'."
},
DOMAIN_CACHES = {
type = "value",
description = "Directory domain 'caches'."
},
DOMAIN_DOCUMENTS = {
type = "value",
description = "Directory domain 'documents'."
},
INTERFACE_ORIENTATION_LANDSCAPE_LEFT = {
type = "value",
description = "Interface orientation UIInterfaceOrientationLandscapeLeft."
},
INTERFACE_ORIENTATION_LANDSCAPE_RIGHT = {
type = "value",
description = "Interface orientation UIInterfaceOrientationLandscapeRight."
},
INTERFACE_ORIENTATION_PORTRAIT = {
type = "value",
description = "Interface orientation UIInterfaceOrientationPortrait."
},
INTERFACE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = {
type = "value",
description = "Interface orientation UIInterfaceOrientationPortraitUpsideDown."
},
SESSION_END = {
type = "value",
description = "Event code indicating the end of an app sessions."
},
SESSION_START = {
type = "value",
description = "Event code indicating the beginning of an app session."
}
}
},
MOAIAudioSampler = {
type = "class",
inherits = "MOAINode",
description = "Audio sampler singleton",
childs = {}
},
MOAIBillingAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for in-app purchase integration on Android devices using either Google Play or Amazon. Exposed to Lua via MOAIBilling on all mobile platforms, but API differs on iOS and Android.",
childs = {
BILLING_PROVIDER_AMAZON = {
type = "value",
description = "Provider code for Amazon."
},
BILLING_PROVIDER_GOOGLE = {
type = "value",
description = "Provider code for Google Play."
},
BILLING_PURCHASE_STATE_ITEM_PURCHASED = {
type = "value",
description = "Purchase state code for a successfully purchased item."
},
BILLING_PURCHASE_STATE_ITEM_REFUNDED = {
type = "value",
description = "Purchase state code for a refunded/revoked purchase."
},
BILLING_PURCHASE_STATE_PURCHASE_CANCELED = {
type = "value",
description = "Purchase state code for a canceled purchase."
},
BILLING_RESULT_BILLING_UNAVAILABLE = {
type = "value",
description = "Error code for a billing request attempted with no billing provider present."
},
BILLING_RESULT_ERROR = {
type = "value",
description = "Error code for a billing request error."
},
BILLING_RESULT_ITEM_UNAVAILABLE = {
type = "value",
description = "Error code for a billing request for an unavailable item."
},
BILLING_RESULT_SUCCESS = {
type = "value",
description = "Error code for a successful billing request."
},
BILLING_RESULT_USER_CANCELED = {
type = "value",
description = "Error code for a billing request canceled by the user, if detected."
},
CHECK_BILLING_SUPPORTED = {
type = "value",
description = "Event code for billing support request completion."
},
PURCHASE_RESPONSE_RECEIVED = {
type = "value",
description = "Event code for item purchase request receipt."
},
PURCHASE_STATE_CHANGED = {
type = "value",
description = "Event code for item purchase state change (purchased, refunded, etc.)."
},
RESTORE_RESPONSE_RECEIVED = {
type = "value",
description = "Event code for restore purchases request receipt."
},
USER_ID_DETERMINED = {
type = "value",
description = "Event code for user ID request completion."
},
checkBillingSupported = {
type = "function",
description = "Check to see if the currently selected billing provider is available.\n\n<– boolean success: True, if the request was successfully initiated.",
args = "()",
returns = "boolean success",
valuetype = "boolean"
},
checkInAppSupported = {
type = "function",
description = "Check to see if the device can get in app billing\n\n<– boolean success",
args = "()",
returns = "boolean success",
valuetype = "boolean"
},
checkSubscriptionSupported = {
type = "function",
description = "Check to see if the device can get subscription billing\n\n<– boolean success",
args = "()",
returns = "boolean success",
valuetype = "boolean"
},
confirmNotification = {
type = "function",
description = "Confirm a previously received notification. Only applies to the Google Play billing provider.\n\n–> string notification: The notification ID to confirm.\n<– boolean success: True, if the request was successfully initiated.",
args = "string notification",
returns = "boolean success",
valuetype = "boolean"
},
consumePurchaseSync = {
type = "function",
description = "Consumes a purchase\n\n–> string token\n<– nil",
args = "string token",
returns = "nil"
},
getPurchasedProducts = {
type = "function",
description = "Gets the user's purchased products\n\n–> number type\n[–> string continuation]\n<– string products: JSON string of products",
args = "(number type, [string continuation])",
returns = "string products",
valuetype = "string"
},
getUserId = {
type = "function",
description = "Get the ID of the current user for the currently selected billing provider. Only applies to the Amazon billing provider.\n\n<– boolean success: True, if the request was successfully initiated.",
args = "()",
returns = "boolean success",
valuetype = "boolean"
},
purchaseProduct = {
type = "function",
description = "Starts a purchase intent for the desired product\n\n–> string sku\n–> number type\n[–> string devPayload]\n<– nil",
args = "(string sku, number type, [string devPayload])",
returns = "nil"
},
requestProductsSync = {
type = "function",
description = "Gets the products from Google Play for the current app\n\n–> table skus\n–> number type\n<– string products: JSON string of products",
args = "(table skus, number type)",
returns = "string products",
valuetype = "string"
},
requestPurchase = {
type = "function",
description = "Request the purchase of an item.\n\n–> string sku: The SKU to purchase.\n[–> string payload: The request payload to be returned upon request completion. Default is nil.]\n<– boolean success: True, if the request was successfully initiated.",
args = "(string sku, [string payload])",
returns = "boolean success",
valuetype = "boolean"
},
restoreTransactions = {
type = "function",
description = "Request the restoration of any previously purchased items.\n\n[–> string offset: The offset in the paginated results to start from. Only applies to the Amazon billing provider. Default is nil.]\n<– boolean success: True, if the request was successfully initiated.",
args = "[string offset]",
returns = "boolean success",
valuetype = "boolean"
},
setBillingProvider = {
type = "function",
description = "Set the billing provider to use for in-app purchases.\n\n–> number provider: The billing provider.\n<– boolean success: True, if the provider was successfully set.",
args = "number provider",
returns = "boolean success",
valuetype = "boolean"
},
setPublicKey = {
type = "function",
description = "Set the public key to be used for receipt verification. Only applies to the Google Play billing provider.\n\n–> string key: The public key.\n<– nil",
args = "string key",
returns = "nil"
}
}
},
MOAIBillingIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for in-app purchase integration on iOS devices using Apple StoreKit. Exposed to Lua via MOAIBilling on all mobile platforms, but API differs on iOS and Android.",
childs = {
PAYMENT_QUEUE_ERROR = {
type = "value",
description = "Event invoked when a transaction fails."
},
PAYMENT_QUEUE_TRANSACTION = {
type = "value",
description = "Event invoked when a transaction changes state."
},
PRODUCT_REQUEST_RESPONSE = {
type = "value",
description = "Event invoked when a product information request completes."
},
PRODUCT_RESTORE_FINISHED = {
type = "value",
description = "Event invoked when a transactions restore is finished."
},
TRANSACTION_STATE_CANCELLED = {
type = "value",
description = "Error code indicating a canceled transaction."
},
TRANSACTION_STATE_FAILED = {
type = "value",
description = "Error code indicating a failed transaction."
},
TRANSACTION_STATE_PURCHASED = {
type = "value",
description = "Error code indicating a completed transaction."
},
TRANSACTION_STATE_PURCHASING = {
type = "value",
description = "Error code indicating a transaction in progress."
},
TRANSACTION_STATE_RESTORED = {
type = "value",
description = "Error code indicating a restored transaction."
}
}
},
MOAIBitmapFontReader = {
type = "class",
inherits = "MOAIFontReader MOAILuaObject",
description = "Legacy font reader for Moai's original bitmap font format. The original format is just a bitmap containing each glyph in the font divided by solid-color guide lines (see examples). This is an easy way for artists to create bitmap fonts. Kerning is not supported by this format.\nRuntime use of MOAIBitmapFontReader is not recommended. Instead, use MOAIBitmapFontReader as part of your tool chain to initialize a glyph cache and image to be serialized in later.",
childs = {
loadPage = {
type = "method",
description = "Rips a set of glyphs from a bitmap and associates them with a size.\n\n–> MOAIBitmapFontReader self\n–> string filename: Filename of the image containing the bitmap font.\n–> string charCodes: A string which defines the characters found in the bitmap\n–> number points: The point size to be associated with the glyphs ripped from the bitmap.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAIBitmapFontReader self, string filename, string charCodes, number points, [number dpi])",
returns = "nil"
}
}
},
MOAIBlocker = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIBoundsDeck = {
type = "class",
inherits = "MOAIDeck",
description = "Deck of bounding boxes. Bounding boxes are allocated in a separate array from that used for box indices. The index array is used to map deck indices onto bounding boxes. In other words there may be more indices then boxes thus allowing for re-use of boxes over multiple indices.\nThe main purpose of the bounds deck is to override the default bounds of elements inside of another deck. The bounds deck may be attached to any other type of deck by using MOAIDeck's setBoundsDeck () method.",
childs = {
reserveBounds = {
type = "method",
description = "Reserve an array of bounds to be indexed.\n\n–> MOAIBoundsDeck self\n–> number nBounds\n<– nil",
args = "(MOAIBoundsDeck self, number nBounds)",
returns = "nil"
},
reserveIndices = {
type = "method",
description = "Reserve indices. Each index maps a deck item onto a bounding box.\n\n–> MOAIBoundsDeck self\n–> number nIndices\n<– nil",
args = "(MOAIBoundsDeck self, number nIndices)",
returns = "nil"
},
setBounds = {
type = "method",
description = "Set the dimensions of a bounding box at a given index.\n\n–> MOAIBoundsDeck self\n–> number idx\n–> number xMin\n–> number yMin\n–> number zMin\n–> number xMax\n–> number yMax\n–> number zMax\n<– nil",
args = "(MOAIBoundsDeck self, number idx, number xMin, number yMin, number zMin, number xMax, number yMax, number zMax)",
returns = "nil"
},
setIndex = {
type = "method",
description = "Associate a deck index with a bounding box.\n\n–> MOAIBoundsDeck self\n–> number idx\n–> number boundsID\n<– nil",
args = "(MOAIBoundsDeck self, number idx, number boundsID)",
returns = "nil"
}
}
},
MOAIBox2DArbiter = {
type = "class",
inherits = "MOAILuaObject b2ContactListener",
description = "Box2D Arbiter.",
childs = {
ALL = {
type = "value"
},
BEGIN = {
type = "value"
},
END = {
type = "value"
},
POST_SOLVE = {
type = "value"
},
PRE_SOLVE = {
type = "value"
},
getContactNormal = {
type = "method",
description = "Returns the normal for the contact.\n\n–> MOAIBox2DArbiter self\n<– number normal.x\n<– number normal.y",
args = "MOAIBox2DArbiter self",
returns = "(number normal.x, number normal.y)",
valuetype = "number"
},
getNormalImpulse = {
type = "method",
description = "Returns total normal impulse for contact.\n\n–> MOAIBox2DArbiter self\n<– number impulse: Impulse in kg * units / s converted from kg * m / s",
args = "MOAIBox2DArbiter self",
returns = "number impulse",
valuetype = "number"
},
getTangentImpulse = {
type = "method",
description = "Returns total tangent impulse for contact.\n\n–> MOAIBox2DArbiter self\n<– number impulse: Impulse in kg * units / s converted from kg * m / s",
args = "MOAIBox2DArbiter self",
returns = "number impulse",
valuetype = "number"
},
setContactEnabled = {
type = "method",
description = "Enabled or disable the contact.\n\n–> MOAIBox2DArbiter self\n–> boolean enabled\n<– nil",
args = "(MOAIBox2DArbiter self, boolean enabled)",
returns = "nil"
}
}
},
MOAIBox2DBody = {
type = "class",
inherits = "MOAIBox2DPrim MOAITransformBase",
description = "Box2D body.",
childs = {
DYNAMIC = {
type = "value"
},
KINEMATIC = {
type = "value"
},
STATIC = {
type = "value"
},
addChain = {
type = "method",
description = "Create and add a set of collision edges to the body.\n\n–> MOAIBox2DBody self\n–> table verts: Array containing vertex coordinate components ( t[1] = x0, t[2] = y0, t[3] = x1, t[4] = y1... )\n[–> boolean closeChain: Default value is false.]\n<– MOAIBox2DFixture fixture: Returns nil on failure.",
args = "(MOAIBox2DBody self, table verts, [boolean closeChain])",
returns = "MOAIBox2DFixture fixture",
valuetype = "MOAIBox2DFixture"
},
addCircle = {
type = "method",
description = "Create and add circle fixture to the body.\n\n–> MOAIBox2DBody self\n–> number x: in units, world coordinates, converted to meters\n–> number y: in units, world coordinates, converted to meters\n–> number radius: in units, converted to meters\n<– MOAIBox2DFixture fixture",
args = "(MOAIBox2DBody self, number x, number y, number radius)",
returns = "MOAIBox2DFixture fixture",
valuetype = "MOAIBox2DFixture"
},
addEdges = {
type = "method",
description = "Create and add a polygon fixture to the body.\n\n–> MOAIBox2DBody self\n–> table verts: Array containing vertex coordinate components in units, world coordinates, converted to meters ( t[1] = x0, t[2] = y0, t[3] = x1, t[4] = y1... )\n<– table fixtures: Array containing MOAIBox2DFixture fixtures. Returns nil on failure.",
args = "(MOAIBox2DBody self, table verts)",
returns = "table fixtures",
valuetype = "table"
},
addPolygon = {
type = "method",
description = "Create and add a polygon fixture to the body.\n\n–> MOAIBox2DBody self\n–> table verts: Array containing vertex coordinate components in units, world coordinates, converted to meters. ( t[1] = x0, t[2] = y0, t[3] = x1, t[4] = y1... )\n<– MOAIBox2DFixture fixture: Returns nil on failure.",
args = "(MOAIBox2DBody self, table verts)",
returns = "MOAIBox2DFixture fixture",
valuetype = "MOAIBox2DFixture"
},
addRect = {
type = "method",
description = "Create and add a rect fixture to the body.\n\n–> MOAIBox2DBody self\n–> number xMin: in units, world coordinates, converted to meters\n–> number yMin: in units, world coordinates, converted to meters\n–> number xMax: in units, world coordinates, converted to meters\n–> number yMax: in units, world coordinates, converted to meters\n–> number angle\n<– MOAIBox2DFixture fixture",
args = "(MOAIBox2DBody self, number xMin, number yMin, number xMax, number yMax, number angle)",
returns = "MOAIBox2DFixture fixture",
valuetype = "MOAIBox2DFixture"
},
applyAngularImpulse = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number angularImpulse: in kg * units / s, converted to kg * m / s\n<– nil",
args = "(MOAIBox2DBody self, number angularImpulse)",
returns = "nil"
},
applyForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number forceX: in kg * units / s^2, converted to N [kg * m / s^2]\n–> number forceY: in kg * units / s^2, converted to N [kg * m / s^2]\n[–> number pointX: in units, world coordinates, converted to meters]\n[–> number pointY: in units, world coordinates, converted to meters]\n<– nil",
args = "(MOAIBox2DBody self, number forceX, number forceY, [number pointX, [number pointY]])",
returns = "nil"
},
applyLinearImpulse = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number impulseX: in kg * units / s, converted to kg * m / s\n–> number impulseY: in kg * units / s, converted to kg * m / s\n[–> number pointX: in units, world coordinates, converted to meters]\n[–> number pointY: in units, world coordinates, converted to meters]\n<– nil",
args = "(MOAIBox2DBody self, number impulseX, number impulseY, [number pointX, [number pointY]])",
returns = "nil"
},
applyTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> number torque: in (kg * units / s^2) * units, converted to N-m. Default value is 0.]\n<– nil",
args = "(MOAIBox2DBody self, [number torque])",
returns = "nil"
},
destroy = {
type = "method",
description = "Schedule body for destruction.\n\n–> MOAIBox2DBody self\n<– nil",
args = "MOAIBox2DBody self",
returns = "nil"
},
getAngle = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number angle: Angle in degrees, converted from radians",
args = "MOAIBox2DBody self",
returns = "number angle",
valuetype = "number"
},
getAngularVelocity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number omega: Angular velocity in degrees/s, converted from radians/s",
args = "MOAIBox2DBody self",
returns = "number omega",
valuetype = "number"
},
getInertia = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number inertia: Calculated inertia (based on last call to resetMassData()). In kg * unit/s^s, converted from kg*m/s^2.",
args = "MOAIBox2DBody self",
returns = "number inertia",
valuetype = "number"
},
getLinearVelocity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number velocityX: in unit/s, converted from m/s\n<– number velocityY: in unit/s, converted from m/s",
args = "MOAIBox2DBody self",
returns = "(number velocityX, number velocityY)",
valuetype = "number"
},
getLocalCenter = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number centerX: in units, local coordinates, converted from meters\n<– number centerY: in units, local coordinates, converted from meters",
args = "MOAIBox2DBody self",
returns = "(number centerX, number centerY)",
valuetype = "number"
},
getMass = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number mass: Calculated mass in kg (based on last call to resetMassData()).",
args = "MOAIBox2DBody self",
returns = "number mass",
valuetype = "number"
},
getPosition = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number positionX: in units, world coordinates, converted from meters\n<– number positionY: in units, world coordinates, converted from meters",
args = "MOAIBox2DBody self",
returns = "(number positionX, number positionY)",
valuetype = "number"
},
getWorldCenter = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– number worldX: in units, world coordinates, converted from meters\n<– number worldY: in units, world coordinates, converted from meters",
args = "MOAIBox2DBody self",
returns = "(number worldX, number worldY)",
valuetype = "number"
},
isActive = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– boolean isActive",
args = "MOAIBox2DBody self",
returns = "boolean isActive",
valuetype = "boolean"
},
isAwake = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– boolean isAwake",
args = "MOAIBox2DBody self",
returns = "boolean isAwake",
valuetype = "boolean"
},
isBullet = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– boolean isBullet",
args = "MOAIBox2DBody self",
returns = "boolean isBullet",
valuetype = "boolean"
},
isFixedRotation = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– boolean isFixedRotation",
args = "MOAIBox2DBody self",
returns = "boolean isFixedRotation",
valuetype = "boolean"
},
resetMassData = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n<– nil",
args = "MOAIBox2DBody self",
returns = "nil"
},
setActive = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> boolean active: Default value is false.]\n<– nil",
args = "(MOAIBox2DBody self, [boolean active])",
returns = "nil"
},
setAngularDamping = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number damping\n<– nil",
args = "(MOAIBox2DBody self, number damping)",
returns = "nil"
},
setAngularVelocity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> number omega: Angular velocity in degrees/s, converted to radians/s. Default value is 0.]\n<– nil",
args = "(MOAIBox2DBody self, [number omega])",
returns = "nil"
},
setAwake = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> boolean awake: Default value is true.]\n<– nil",
args = "(MOAIBox2DBody self, [boolean awake])",
returns = "nil"
},
setBullet = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> boolean bullet: Default value is true.]\n<– nil",
args = "(MOAIBox2DBody self, [boolean bullet])",
returns = "nil"
},
setFixedRotation = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> boolean fixedRotation: Default value is true.]\n<– nil",
args = "(MOAIBox2DBody self, [boolean fixedRotation])",
returns = "nil"
},
setLinearDamping = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> number damping]\n<– nil",
args = "(MOAIBox2DBody self, [number damping])",
returns = "nil"
},
setLinearVelocity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> number velocityX: in unit/s, converted to m/s. Default is 0.]\n[–> number velocityY: in unit/s, converted to m/s. Default is 0.]\n<– nil",
args = "(MOAIBox2DBody self, [number velocityX, [number velocityY]])",
returns = "nil"
},
setMassData = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number mass: in kg.\n[–> number I: in kg*units^2, converted to kg * m^2. Default is previous value for I.]\n[–> number centerX: in units, local coordinates, converted to meters. Default is previous value for centerX.]\n[–> number centerY: in units, local coordinates, converted to meters. Default is previous value for centerY.]\n<– nil",
args = "(MOAIBox2DBody self, number mass, [number I, [number centerX, [number centerY]]])",
returns = "nil"
},
setTransform = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n[–> number positionX: in units, world coordinates, converted to meters. Default is 0.]\n[–> number positionY: in units, world coordinates, converted to meters. Default is 0.]\n[–> number angle: In degrees, converted to radians. Default is 0.]\n<– nil",
args = "(MOAIBox2DBody self, [number positionX, [number positionY, [number angle]]])",
returns = "nil"
},
setType = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DBody self\n–> number type: One of MOAIBox2DBody.DYNAMIC, MOAIBox2DBody.KINEMATIC, MOAIBox2DBody.STATIC\n<– nil",
args = "(MOAIBox2DBody self, number type)",
returns = "nil"
}
}
},
MOAIBox2DDistanceJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D distance joint.",
childs = {
getDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n<– number dampingRatio",
args = "MOAIBox2DDistanceJoint self",
returns = "number dampingRatio",
valuetype = "number"
},
getFrequency = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n<– number frequency: In Hz.",
args = "MOAIBox2DDistanceJoint self",
returns = "number frequency",
valuetype = "number"
},
getLength = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n<– number length: In units, converted from meters.",
args = "MOAIBox2DDistanceJoint self",
returns = "number length",
valuetype = "number"
},
setDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n[–> number dampingRatio: Default value is 0.]\n<– nil",
args = "(MOAIBox2DDistanceJoint self, [number dampingRatio])",
returns = "nil"
},
setFrequency = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n[–> number frequency: In Hz. Default value is 0.]\n<– nil",
args = "(MOAIBox2DDistanceJoint self, [number frequency])",
returns = "nil"
},
setLength = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DDistanceJoint self\n[–> number length: in units, converted to meters. Default value is 0.]\n<– nil",
args = "(MOAIBox2DDistanceJoint self, [number length])",
returns = "nil"
}
}
},
MOAIBox2DFixture = {
type = "class",
inherits = "MOAIBox2DPrim MOAILuaObject",
description = "Box2D fixture.",
childs = {
destroy = {
type = "method",
description = "Schedule fixture for destruction.\n\n–> MOAIBox2DFixture self\n<– nil",
args = "MOAIBox2DFixture self",
returns = "nil"
},
getBody = {
type = "method",
description = "Returns the body that owns the fixture.\n\n–> MOAIBox2DFixture self\n<– MOAIBox2DBody body",
args = "MOAIBox2DFixture self",
returns = "MOAIBox2DBody body",
valuetype = "MOAIBox2DBody"
},
getFilter = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n<– number categoryBits\n<– number maskBits\n<– number groupIndex",
args = "MOAIBox2DFixture self",
returns = "(number categoryBits, number maskBits, number groupIndex)",
valuetype = "number"
},
setCollisionHandler = {
type = "method",
description = "Sets a Lua function to call when collisions occur. The handler should accept the following parameters: ( phase, fixtureA, fixtureB, arbiter ). 'phase' will be one of the phase masks. 'fixtureA' will be the fixture receiving the collision. 'fixtureB' will be the other fixture in the collision. 'arbiter' will be the MOAIArbiter. Note that the arbiter is only good for the current collision: do not keep references to it for later use.\n\n–> MOAIBox2DFixture self\n–> function handler\n[–> number phaseMask: Any bitwise combination of MOAIBox2DArbiter.BEGIN, MOAIBox2DArbiter.END, MOAIBox2DArbiter.POST_SOLVE, MOAIBox2DArbiter.PRE_SOLVE, MOAIBox2DArbiter.ALL]\n[–> number categoryMask: Check against opposing fixture's category bits and generate collision events if match.]\n<– nil",
args = "(MOAIBox2DFixture self, function handler, [number phaseMask, [number categoryMask]])",
returns = "nil"
},
setDensity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n–> number density: In kg/units^2, converted to kg/m^2\n<– nil",
args = "(MOAIBox2DFixture self, number density)",
returns = "nil"
},
setFilter = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n–> number categoryBits\n[–> number maskBits]\n[–> number groupIndex]\n<– nil",
args = "(MOAIBox2DFixture self, number categoryBits, [number maskBits, [number groupIndex]])",
returns = "nil"
},
setFriction = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n–> number friction\n<– nil",
args = "(MOAIBox2DFixture self, number friction)",
returns = "nil"
},
setRestitution = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n–> number restitution\n<– nil",
args = "(MOAIBox2DFixture self, number restitution)",
returns = "nil"
},
setSensor = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFixture self\n[–> boolean isSensor: Default value is 'true']\n<– nil",
args = "(MOAIBox2DFixture self, [boolean isSensor])",
returns = "nil"
}
}
},
MOAIBox2DFrictionJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D friction joint.",
childs = {
getMaxForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFrictionJoint self\n<– number maxForce: in kg * units / s^2, converted from N [kg * m / s^2].",
args = "MOAIBox2DFrictionJoint self",
returns = "number maxForce",
valuetype = "number"
},
getMaxTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFrictionJoint self\n<– number maxTorque: in (kg * units / s^2) * units, converted from N-m.",
args = "MOAIBox2DFrictionJoint self",
returns = "number maxTorque",
valuetype = "number"
},
setMaxForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFrictionJoint self\n[–> number maxForce: in kg * units / s^2, converted to N [kg * m / s^2]. Default value is 0.]\n<– nil",
args = "(MOAIBox2DFrictionJoint self, [number maxForce])",
returns = "nil"
},
setMaxTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DFrictionJoint self\n[–> number maxTorque: in (kg * units / s^2) * units, converted to N-m. Default value is 0.]\n<– nil",
args = "(MOAIBox2DFrictionJoint self, [number maxTorque])",
returns = "nil"
}
}
},
MOAIBox2DGearJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D gear joint.",
childs = {
getJointA = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DGearJoint self\n<– MOAIBox2DJoint jointA",
args = "MOAIBox2DGearJoint self",
returns = "MOAIBox2DJoint jointA",
valuetype = "MOAIBox2DJoint"
},
getJointB = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DGearJoint self\n<– MOAIBox2DJoint jointB",
args = "MOAIBox2DGearJoint self",
returns = "MOAIBox2DJoint jointB",
valuetype = "MOAIBox2DJoint"
},
getRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DGearJoint self\n<– number ratio",
args = "MOAIBox2DGearJoint self",
returns = "number ratio",
valuetype = "number"
},
setRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DGearJoint self\n[–> number ratio: Default value is 0.]\n<– nil",
args = "(MOAIBox2DGearJoint self, [number ratio])",
returns = "nil"
}
}
},
MOAIBox2DJoint = {
type = "class",
inherits = "MOAIBox2DPrim",
description = "Box2D joint.",
childs = {
destroy = {
type = "method",
description = "Schedule joint for destruction.\n\n–> MOAIBox2DJoint self\n<– nil",
args = "MOAIBox2DJoint self",
returns = "nil"
},
getAnchorA = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– number anchorX: in units, in world coordinates, converted to meters\n<– number anchorY: in units, in world coordinates, converted to meters",
args = "MOAIBox2DJoint self",
returns = "(number anchorX, number anchorY)",
valuetype = "number"
},
getAnchorB = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– number anchorX: in units, in world coordinates, converted from meters\n<– number anchorY: in units, in world coordinates, converted from meters",
args = "MOAIBox2DJoint self",
returns = "(number anchorX, number anchorY)",
valuetype = "number"
},
getBodyA = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– MOAIBox2DBody body",
args = "MOAIBox2DJoint self",
returns = "MOAIBox2DBody body",
valuetype = "MOAIBox2DBody"
},
getBodyB = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– MOAIBox2DBody body",
args = "MOAIBox2DJoint self",
returns = "MOAIBox2DBody body",
valuetype = "MOAIBox2DBody"
},
getReactionForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– number forceX: in kg * units / s^2 converted from N [kg * m / s^2]\n<– number forceY: in kg * units / s^2 converted from N [kg * m / s^2]",
args = "MOAIBox2DJoint self",
returns = "(number forceX, number forceY)",
valuetype = "number"
},
getReactionTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DJoint self\n<– number reactionTorque: in (kg * units / s^2) * units, converted from N-m.",
args = "MOAIBox2DJoint self",
returns = "number reactionTorque",
valuetype = "number"
}
}
},
MOAIBox2DMouseJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D 'mouse' joint.",
childs = {
getDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n<– number dampingRatio",
args = "MOAIBox2DMouseJoint self",
returns = "number dampingRatio",
valuetype = "number"
},
getFrequency = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n<– number frequency: in Hz",
args = "MOAIBox2DMouseJoint self",
returns = "number frequency",
valuetype = "number"
},
getMaxForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n<– number maxForce: in kg * units / s^2 converted from N [kg * m / s^2]",
args = "MOAIBox2DMouseJoint self",
returns = "number maxForce",
valuetype = "number"
},
getTarget = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n<– number x: in units, world coordinates, converted from meters\n<– number y: in units, world coordinates, converted from meters",
args = "MOAIBox2DMouseJoint self",
returns = "(number x, number y)",
valuetype = "number"
},
setDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n[–> number dampingRatio: Default value is 0.]\n<– nil",
args = "(MOAIBox2DMouseJoint self, [number dampingRatio])",
returns = "nil"
},
setFrequency = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n[–> number frequency: in Hz. Default value is 0.]\n<– nil",
args = "(MOAIBox2DMouseJoint self, [number frequency])",
returns = "nil"
},
setMaxForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n[–> number maxForce: in kg * units / s^2 converted to N [kg * m / s^2]. Default value is 0.]\n<– nil",
args = "(MOAIBox2DMouseJoint self, [number maxForce])",
returns = "nil"
},
setTarget = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DMouseJoint self\n[–> number x: in units, world coordinates, converted to meters. Default value is 0.]\n[–> number y: in units, world coordinates, converted to meters. Default value is 0.]\n<– nil",
args = "(MOAIBox2DMouseJoint self, [number x, [number y]])",
returns = "nil"
}
}
},
MOAIBox2DPrim = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIBox2DPrismaticJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D prismatic joint.",
childs = {
getJointSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number jointSpeed: in units/s, converted from m/s",
args = "MOAIBox2DPrismaticJoint self",
returns = "number jointSpeed",
valuetype = "number"
},
getJointTranslation = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number jointTranslation: in units, converted from meters.",
args = "MOAIBox2DPrismaticJoint self",
returns = "number jointTranslation",
valuetype = "number"
},
getLowerLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number lowerLimit: in units, converted from meters.",
args = "MOAIBox2DPrismaticJoint self",
returns = "number lowerLimit",
valuetype = "number"
},
getMotorForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number motorForce: in kg * units / s^2, converted from N [kg * m / s^2]",
args = "MOAIBox2DPrismaticJoint self",
returns = "number motorForce",
valuetype = "number"
},
getMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number motorSpeed: in units/s, converted from m/s",
args = "MOAIBox2DPrismaticJoint self",
returns = "number motorSpeed",
valuetype = "number"
},
getUpperLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– number upperLimit: in units, converted from meters.",
args = "MOAIBox2DPrismaticJoint self",
returns = "number upperLimit",
valuetype = "number"
},
isLimitEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– boolean limitEnabled",
args = "MOAIBox2DPrismaticJoint self",
returns = "boolean limitEnabled",
valuetype = "boolean"
},
isMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n<– boolean motorEnabled",
args = "MOAIBox2DPrismaticJoint self",
returns = "boolean motorEnabled",
valuetype = "boolean"
},
setLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n[–> number lower: in units, converted to meters. Default value is 0.]\n[–> number upper: in units, converted to meters. Default value is 0.]\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [number lower, [number upper]])",
returns = "nil"
},
setLimitEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n[–> boolean enabled: Default value is 'true']\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [boolean enabled])",
returns = "nil"
},
setMaxMotorForce = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n[–> number maxMotorForce: in kg * units / s^2, converted to N [kg * m / s^2]. Default value is 0.]\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [number maxMotorForce])",
returns = "nil"
},
setMotor = {
type = "method",
description = "See Box2D documentation. If speed is determined to be zero, the motor is disabled, unless forceEnable is set.\n\n–> MOAIBox2DPrismaticJoint self\n[–> number speed: in units/s converted to m/s. Default value is 0.]\n[–> number maxForce: in kg * units / s^2, converted to N [kg * m / s^2]. Default value is 0.]\n[–> boolean forceEnable: Default value is false.]\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [number speed, [number maxForce, [boolean forceEnable]]])",
returns = "nil"
},
setMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n[–> boolean enabled: Default value is 'true']\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [boolean enabled])",
returns = "nil"
},
setMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPrismaticJoint self\n[–> number motorSpeed: in units/s, converted to m/s. Default value is 0.]\n<– nil",
args = "(MOAIBox2DPrismaticJoint self, [number motorSpeed])",
returns = "nil"
}
}
},
MOAIBox2DPulleyJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D pulley joint.",
childs = {
getGroundAnchorA = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPulleyJoint self\n<– number x: in units, world coordinates, converted from meters\n<– number y: in units, world coordinates, converted from meters",
args = "MOAIBox2DPulleyJoint self",
returns = "(number x, number y)",
valuetype = "number"
},
getGroundAnchorB = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPulleyJoint self\n<– number x: in units, world coordinates, converted from meters\n<– number y: in units, world coordinates, converted from meters",
args = "MOAIBox2DPulleyJoint self",
returns = "(number x, number y)",
valuetype = "number"
},
getLength1 = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPulleyJoint self\n<– number length1: in units, converted from meters.",
args = "MOAIBox2DPulleyJoint self",
returns = "number length1",
valuetype = "number"
},
getLength2 = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPulleyJoint self\n<– number length2: in units, converted from meters.",
args = "MOAIBox2DPulleyJoint self",
returns = "number length2",
valuetype = "number"
},
getRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DPulleyJoint self\n<– number ratio",
args = "MOAIBox2DPulleyJoint self",
returns = "number ratio",
valuetype = "number"
}
}
},
MOAIBox2DRevoluteJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D revolute joint.",
childs = {
getJointAngle = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number angle: in degrees, converted from radians",
args = "MOAIBox2DRevoluteJoint self",
returns = "number angle",
valuetype = "number"
},
getJointSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number jointSpeed: in degrees/s, converted from radians/s",
args = "MOAIBox2DRevoluteJoint self",
returns = "number jointSpeed",
valuetype = "number"
},
getLowerLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number lowerLimit: in degrees, converted from radians",
args = "MOAIBox2DRevoluteJoint self",
returns = "number lowerLimit",
valuetype = "number"
},
getMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number motorSpeed: in degrees/s, converted from radians/s",
args = "MOAIBox2DRevoluteJoint self",
returns = "number motorSpeed",
valuetype = "number"
},
getMotorTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number motorTorque: in (kg * units / s^2) * units, converted from N-m..",
args = "MOAIBox2DRevoluteJoint self",
returns = "number motorTorque",
valuetype = "number"
},
getUpperLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– number upperLimit: in degrees, converted from radians",
args = "MOAIBox2DRevoluteJoint self",
returns = "number upperLimit",
valuetype = "number"
},
isLimitEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– boolean limitEnabled",
args = "MOAIBox2DRevoluteJoint self",
returns = "boolean limitEnabled",
valuetype = "boolean"
},
isMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n<– boolean motorEnabled",
args = "MOAIBox2DRevoluteJoint self",
returns = "boolean motorEnabled",
valuetype = "boolean"
},
setLimit = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n[–> number lower: in degrees, converted to radians. Default value is 0.]\n[–> number upper: in degrees, converted to radians. Default value is 0.]\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [number lower, [number upper]])",
returns = "nil"
},
setLimitEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n[–> boolean enabled: Default value is 'true']\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [boolean enabled])",
returns = "nil"
},
setMaxMotorTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n[–> number maxMotorTorque: in (kg * units / s^2) * units, converted to N-m. Default value is 0.]\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [number maxMotorTorque])",
returns = "nil"
},
setMotor = {
type = "method",
description = "See Box2D documentation. If speed is determined to be zero, the motor is disabled, unless forceEnable is set.\n\n–> MOAIBox2DRevoluteJoint self\n[–> number speed: in degrees/s, converted to radians/s. Default value is 0.]\n[–> number maxMotorTorque: in (kg * units / s^2) * units, converted to N-m. Default value is 0.]\n[–> boolean forceEnable: Default value is false.]\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [number speed, [number maxMotorTorque, [boolean forceEnable]]])",
returns = "nil"
},
setMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n[–> boolean enabled: Default value is 'true']\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [boolean enabled])",
returns = "nil"
},
setMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRevoluteJoint self\n[–> number motorSpeed: in degrees/s, converted to radians/s. Default value is 0.]\n<– nil",
args = "(MOAIBox2DRevoluteJoint self, [number motorSpeed])",
returns = "nil"
}
}
},
MOAIBox2DRopeJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D rope joint.",
childs = {
getLimitState = {
type = "method",
description = 'See Box2D documentation.\n\n–> MOAIBox2DRopeJoint self\n<– number limitState: one of the "LimitState" codes',
args = "MOAIBox2DRopeJoint self",
returns = "number limitState",
valuetype = "number"
},
getMaxLength = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRopeJoint self\n<– number maxLength: in units, converted from meters.",
args = "MOAIBox2DRopeJoint self",
returns = "number maxLength",
valuetype = "number"
},
setMaxLength = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DRopeJoint self\n–> number maxLength: in units, converted to meters. Default is 0.\n<– nil",
args = "(MOAIBox2DRopeJoint self, number maxLength)",
returns = "nil"
}
}
},
MOAIBox2DWeldJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D weld joint.",
childs = {}
},
MOAIBox2DWheelJoint = {
type = "class",
inherits = "MOAIBox2DJoint",
description = "Box2D wheel joint.",
childs = {
getJointSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number jointSpeed: in units / s, converted from m/s",
args = "MOAIBox2DWheelJoint self",
returns = "number jointSpeed",
valuetype = "number"
},
getJointTranslation = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number jointTranslation: in units, converted from meters",
args = "MOAIBox2DWheelJoint self",
returns = "number jointTranslation",
valuetype = "number"
},
getMaxMotorTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number maxMotorTorque: in (kg * units / s^2) * units, converted from N-m.",
args = "MOAIBox2DWheelJoint self",
returns = "number maxMotorTorque",
valuetype = "number"
},
getMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number motorSpeed: in degrees/s, converted from radians/s",
args = "MOAIBox2DWheelJoint self",
returns = "number motorSpeed",
valuetype = "number"
},
getMotorTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number torque: in (kg * units / s^2) * units, converted from N-m.",
args = "MOAIBox2DWheelJoint self",
returns = "number torque",
valuetype = "number"
},
getSpringDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number dampingRatio",
args = "MOAIBox2DWheelJoint self",
returns = "number dampingRatio",
valuetype = "number"
},
getSpringFrequencyHz = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– number springFrequency: in Hz",
args = "MOAIBox2DWheelJoint self",
returns = "number springFrequency",
valuetype = "number"
},
isMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n<– boolean motorEnabled",
args = "MOAIBox2DWheelJoint self",
returns = "boolean motorEnabled",
valuetype = "boolean"
},
setMaxMotorTorque = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n[–> number maxMotorTorque: in (kg * units / s^2) * units, converted to N-m. Default value is 0.]\n<– nil",
args = "(MOAIBox2DWheelJoint self, [number maxMotorTorque])",
returns = "nil"
},
setMotor = {
type = "method",
description = "See Box2D documentation. If speed is determined to be zero, the motor is disabled, unless forceEnable is set.\n\n–> MOAIBox2DWheelJoint self\n[–> number speed: in degrees/s, converted to radians/s. Default value is 0.]\n[–> number maxMotorTorque: in (kg * units / s^2) * units, converted from N-m. Default value is 0.]\n[–> boolean forceEnable: Default value is false.]\n<– nil",
args = "(MOAIBox2DWheelJoint self, [number speed, [number maxMotorTorque, [boolean forceEnable]]])",
returns = "nil"
},
setMotorEnabled = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n[–> boolean enabled: Default value is 'true']\n<– nil",
args = "(MOAIBox2DWheelJoint self, [boolean enabled])",
returns = "nil"
},
setMotorSpeed = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n[–> number motorSpeed: in degrees/s, converted to radians/s. Default value is 0.]\n<– nil",
args = "(MOAIBox2DWheelJoint self, [number motorSpeed])",
returns = "nil"
},
setSpringDampingRatio = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n[–> number dampingRatio: Default value is 0.]\n<– nil",
args = "(MOAIBox2DWheelJoint self, [number dampingRatio])",
returns = "nil"
},
setSpringFrequencyHz = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWheelJoint self\n[–> number springFrequencyHz: in Hz. Default value is 0.]\n<– nil",
args = "(MOAIBox2DWheelJoint self, [number springFrequencyHz])",
returns = "nil"
}
}
},
MOAIBox2DWorld = {
type = "class",
inherits = "MOAIAction b2DestructionListener",
description = "Box2D world.",
childs = {
DEBUG_DRAW_BOUNDS = {
type = "value"
},
DEBUG_DRAW_CENTERS = {
type = "value"
},
DEBUG_DRAW_DEFAULT = {
type = "value"
},
DEBUG_DRAW_JOINTS = {
type = "value"
},
DEBUG_DRAW_PAIRS = {
type = "value"
},
DEBUG_DRAW_SHAPES = {
type = "value"
},
addBody = {
type = "method",
description = "Create and add a body to the world.\n\n–> MOAIBox2DWorld self\n–> number type: One of MOAIBox2DBody.DYNAMIC, MOAIBox2DBody.KINEMATIC, MOAIBox2DBody.STATIC\n[–> number x: in units, in world coordinates, converted to meters]\n[–> number y: in units, in world coordinates, converted to meters]\n<– MOAIBox2DBody joint",
args = "(MOAIBox2DWorld self, number type, [number x, [number y]])",
returns = "MOAIBox2DBody joint",
valuetype = "MOAIBox2DBody"
},
addDistanceJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorA_X: in units, in world coordinates, converted to meters\n–> number anchorA_Y: in units, in world coordinates, converted to meters\n–> number anchorB_X: in units, in world coordinates, converted to meters\n–> number anchorB_Y: in units, in world coordinates, converted to meters\n[–> number frequencyHz: in Hz. Default value determined by Box2D]\n[–> number dampingRatio: Default value determined by Box2D]\n[–> boolean collideConnected: Default value is false]\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorA_X, number anchorA_Y, number anchorB_X, number anchorB_Y, [number frequencyHz, [number dampingRatio, [boolean collideConnected]]])",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addFrictionJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorX: in units, in world coordinates, converted to meters\n–> number anchorY: in units, in world coordinates, converted to meters\n[–> number maxForce: in kg * units / s^2, converted to N [kg * m / s^2]. Default value determined by Box2D]\n[–> number maxTorque: in kg * units / s^2 * units, converted to N-m [kg * m / s^2 * m]. Default value determined by Box2D]\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorX, number anchorY, [number maxForce, [number maxTorque]])",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addGearJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DJoint jointA\n–> MOAIBox2DJoint jointB\n–> number ratio\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DJoint jointA, MOAIBox2DJoint jointB, number ratio)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addMouseJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number targetX: in units, in world coordinates, converted to meters\n–> number targetY: in units, in world coordinates, converted to meters\n–> number maxForce: in kg * units / s^2, converted to N [kg * m / s^2].\n[–> number frequencyHz: in Hz. Default value determined by Box2D]\n[–> number dampingRatio: Default value determined by Box2D]\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number targetX, number targetY, number maxForce, [number frequencyHz, [number dampingRatio]])",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addPrismaticJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorA: in units, in world coordinates, converted to meters\n–> number anchorB: in units, in world coordinates, converted to meters\n–> number axisA: translation axis vector X component (no units)\n–> number axisB: translation axis vector Y component (no units)\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorA, number anchorB, number axisA, number axisB)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addPulleyJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number groundAnchorA_X: in units, in world coordinates, converted to meters\n–> number groundAnchorA_Y: in units, in world coordinates, converted to meters\n–> number groundAnchorB_X: in units, in world coordinates, converted to meters\n–> number groundAnchorB_Y: in units, in world coordinates, converted to meters\n–> number anchorA_X: in units, in world coordinates, converted to meters\n–> number anchorA_Y: in units, in world coordinates, converted to meters\n–> number anchorB_X: in units, in world coordinates, converted to meters\n–> number anchorB_Y: in units, in world coordinates, converted to meters\n–> number ratio\n–> number maxLengthA: in units, converted to meters\n–> number maxLengthB: in units, converted to meters\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number groundAnchorA_X, number groundAnchorA_Y, number groundAnchorB_X, number groundAnchorB_Y, number anchorA_X, number anchorA_Y, number anchorB_X, number anchorB_Y, number ratio, number maxLengthA, number maxLengthB)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addRevoluteJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorX: in units, in world coordinates, converted to meters\n–> number anchorY: in units, in world coordinates, converted to meters\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorX, number anchorY)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addRopeJoint = {
type = "method",
description = "Create and add a rope joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number maxLength: in units, converted to meters\n[–> number anchorAX: in units, in world coordinates, converted to meters]\n[–> number anchorAY: in units, in world coordinates, converted to meters]\n[–> number anchorBX: in units, in world coordinates, converted to meters]\n[–> number anchorBY: in units, in world coordinates, converted to meters]\n[–> boolean collideConnected: Default value is false]\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number maxLength, [number anchorAX, [number anchorAY, [number anchorBX, [number anchorBY, [boolean collideConnected]]]]])",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addWeldJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorX: in units, in world coordinates, converted to meters\n–> number anchorY: in units, in world coordinates, converted to meters\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorX, number anchorY)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
addWheelJoint = {
type = "method",
description = "Create and add a joint to the world. See Box2D documentation.\n\n–> MOAIBox2DWorld self\n–> MOAIBox2DBody bodyA\n–> MOAIBox2DBody bodyB\n–> number anchorX: in units, in world coordinates, converted to meters\n–> number anchorY: in units, in world coordinates, converted to meters\n–> number axisX: translation axis vector X component (no units)\n–> number axisY: translation axis vector Y component (no units)\n<– MOAIBox2DJoint joint",
args = "(MOAIBox2DWorld self, MOAIBox2DBody bodyA, MOAIBox2DBody bodyB, number anchorX, number anchorY, number axisX, number axisY)",
returns = "MOAIBox2DJoint joint",
valuetype = "MOAIBox2DJoint"
},
getAngularSleepTolerance = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n<– number angularSleepTolerance: in degrees/s, converted from radians/s",
args = "MOAIBox2DWorld self",
returns = "number angularSleepTolerance",
valuetype = "number"
},
getAutoClearForces = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n<– boolean autoClearForces",
args = "MOAIBox2DWorld self",
returns = "boolean autoClearForces",
valuetype = "boolean"
},
getGravity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n<– number gravityX: in units/s^2, converted from m/s^2\n<– number gravityY: in units/s^2, converted from m/s^2",
args = "MOAIBox2DWorld self",
returns = "(number gravityX, number gravityY)",
valuetype = "number"
},
getLinearSleepTolerance = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n<– number linearSleepTolerance: in units/s, converted from m/s",
args = "MOAIBox2DWorld self",
returns = "number linearSleepTolerance",
valuetype = "number"
},
getRayCast = {
type = "method",
description = "return RayCast 1st point hit\n\n–> MOAIBox2DWorld self\n–> number p1x\n–> number p1y\n–> number p2x\n–> number p2y\n<– boolean hit: true if hit, false otherwise\n<– MOAIBox2DFixture fixture: the fixture that was hit, or nil\n<– number hitpointX\n<– number hitpointY",
args = "(MOAIBox2DWorld self, number p1x, number p1y, number p2x, number p2y)",
returns = "(boolean hit, MOAIBox2DFixture fixture, number hitpointX, number hitpointY)",
valuetype = "boolean"
},
getTimeToSleep = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n<– number timeToSleep",
args = "MOAIBox2DWorld self",
returns = "number timeToSleep",
valuetype = "number"
},
setAngularSleepTolerance = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> number angularSleepTolerance: in degrees/s, converted to radians/s. Default value is 0.0f.]\n<– nil",
args = "(MOAIBox2DWorld self, [number angularSleepTolerance])",
returns = "nil"
},
setAutoClearForces = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> boolean autoClearForces: Default value is 'true']\n<– nil",
args = "(MOAIBox2DWorld self, [boolean autoClearForces])",
returns = "nil"
},
setDebugDrawEnabled = {
type = "method",
description = "enable/disable debug drawing.\n\n–> MOAIBox2DWorld self\n–> boolean enable\n<– nil",
args = "(MOAIBox2DWorld self, boolean enable)",
returns = "nil"
},
setDebugDrawFlags = {
type = "method",
description = "Sets mask for debug drawing.\n\n–> MOAIBox2DWorld self\n[–> number flags: One of MOAIBox2DWorld.DEBUG_DRAW_SHAPES, MOAIBox2DWorld.DEBUG_DRAW_JOINTS, MOAIBox2DWorld.DEBUG_DRAW_BOUNDS, MOAIBox2DWorld.DEBUG_DRAW_PAIRS, MOAIBox2DWorld.DEBUG_DRAW_CENTERS. Default value is MOAIBox2DWorld.DEBUG_DRAW_DEFAULT.]\n<– nil",
args = "(MOAIBox2DWorld self, [number flags])",
returns = "nil"
},
setGravity = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> number gravityX: in units/s^2, converted to m/s^2. Default value is 0.]\n[–> number gravityY: in units/s^2, converted to m/s^2. Default value is 0.]\n<– nil",
args = "(MOAIBox2DWorld self, [number gravityX, [number gravityY]])",
returns = "nil"
},
setIterations = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> number velocityIteratons: Default value is current value of velocity iterations.]\n[–> number positionIterations: Default value is current value of positions iterations.]\n<– nil",
args = "(MOAIBox2DWorld self, [number velocityIteratons, [number positionIterations]])",
returns = "nil"
},
setLinearSleepTolerance = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> number linearSleepTolerance: in units/s, converted to m/s. Default value is 0.0f.]\n<– nil",
args = "(MOAIBox2DWorld self, [number linearSleepTolerance])",
returns = "nil"
},
setTimeToSleep = {
type = "method",
description = "See Box2D documentation.\n\n–> MOAIBox2DWorld self\n[–> number timeToSleep: Default value is 0.0f.]\n<– nil",
args = "(MOAIBox2DWorld self, [number timeToSleep])",
returns = "nil"
},
setUnitsToMeters = {
type = "method",
description = "Sets a scale factor for converting game world units to Box2D meters.\n\n–> MOAIBox2DWorld self\n[–> number unitsToMeters: Default value is 1.]\n<– nil",
args = "(MOAIBox2DWorld self, [number unitsToMeters])",
returns = "nil"
}
}
},
MOAIBrowserAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for access to the native web browser. Exposed to Lua via MOAIBrowser on all mobile platforms.",
childs = {
canOpenURL = {
type = "function",
description = "Return true if the device has an app installed that can open the URL.\n\n–> string url: The URL to check.\n<– boolean",
args = "string url",
returns = "boolean",
valuetype = "boolean"
},
openURL = {
type = "function",
description = "Open the given URL in the device browser.\n\n–> string url: The URL to open.\n<– nil",
args = "string url",
returns = "nil"
},
openURLWithParams = {
type = "function",
description = "Open the native device web browser at the specified URL with the specified list of query string parameters.\n\n–> string url\n–> table params\n<– nil",
args = "(string url, table params)",
returns = "nil"
}
}
},
MOAIBrowserIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for access to the native web browser. Exposed to Lua via MOAIBrowser on all mobile platforms.",
childs = {}
},
MOAIButtonSensor = {
type = "class",
inherits = "MOAISensor",
description = "Button sensor.",
childs = {
down = {
type = "method",
description = "Checks to see if the button was pressed during the last iteration.\n\n–> MOAIButtonSensor self\n<– boolean wasPressed",
args = "MOAIButtonSensor self",
returns = "boolean wasPressed",
valuetype = "boolean"
},
isDown = {
type = "method",
description = "Checks to see if the button is currently down.\n\n–> MOAIButtonSensor self\n<– boolean isDown",
args = "MOAIButtonSensor self",
returns = "boolean isDown",
valuetype = "boolean"
},
isUp = {
type = "method",
description = "Checks to see if the button is currently up.\n\n–> MOAIButtonSensor self\n<– boolean isUp",
args = "MOAIButtonSensor self",
returns = "boolean isUp",
valuetype = "boolean"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when button events occur.\n\n–> MOAIButtonSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIButtonSensor self, [function callback])",
returns = "nil"
},
up = {
type = "method",
description = "Checks to see if the button was released during the last iteration.\n\n–> MOAIButtonSensor self\n<– boolean wasReleased",
args = "MOAIButtonSensor self",
returns = "boolean wasReleased",
valuetype = "boolean"
}
}
},
MOAICamera = {
type = "class",
inherits = "MOAITransform",
description = "Perspective or orthographic camera.",
childs = {
getFarPlane = {
type = "method",
description = "Returns the camera's far plane.\n\n–> MOAICamera self\n<– number far",
args = "MOAICamera self",
returns = "number far",
valuetype = "number"
},
getFieldOfView = {
type = "method",
description = "Returns the camera's horizontal field of view.\n\n–> MOAICamera self\n<– number hfov",
args = "MOAICamera self",
returns = "number hfov",
valuetype = "number"
},
getFocalLength = {
type = "method",
description = "Returns the camera's focal length given the width of the view plane.\n\n–> MOAICamera self\n–> number width\n<– number length",
args = "(MOAICamera self, number width)",
returns = "number length",
valuetype = "number"
},
getNearPlane = {
type = "method",
description = "Returns the camera's near plane.\n\n–> MOAICamera self\n<– number near",
args = "MOAICamera self",
returns = "number near",
valuetype = "number"
},
setFarPlane = {
type = "method",
description = "Sets the camera's far plane distance.\n\n–> MOAICamera self\n[–> number far: Default value is 10000.]\n<– nil",
args = "(MOAICamera self, [number far])",
returns = "nil"
},
setFieldOfView = {
type = "method",
description = "Sets the camera's horizontal field of view.\n\n–> MOAICamera self\n[–> number hfow: Default value is 60.]\n<– nil",
args = "(MOAICamera self, [number hfow])",
returns = "nil"
},
setNearPlane = {
type = "method",
description = "Sets the camera's near plane distance.\n\n–> MOAICamera self\n[–> number near: Default value is 1.]\n<– nil",
args = "(MOAICamera self, [number near])",
returns = "nil"
},
setOrtho = {
type = "method",
description = "Sets orthographic mode.\n\n–> MOAICamera self\n[–> boolean ortho: Default value is true.]\n<– nil",
args = "(MOAICamera self, [boolean ortho])",
returns = "nil"
}
}
},
MOAICamera2D = {
type = "class",
inherits = "MOAITransform2D",
description = "2D camera.",
childs = {
getFarPlane = {
type = "method",
description = "Returns the camera's far plane.\n\n–> MOAICamera2D self\n<– number far",
args = "MOAICamera2D self",
returns = "number far",
valuetype = "number"
},
getNearPlane = {
type = "method",
description = "Returns the camera's near plane.\n\n–> MOAICamera2D self\n<– number near",
args = "MOAICamera2D self",
returns = "number near",
valuetype = "number"
},
setFarPlane = {
type = "method",
description = "Sets the camera's far plane distance.\n\n–> MOAICamera2D self\n[–> number far: Default value is -1.]\n<– nil",
args = "(MOAICamera2D self, [number far])",
returns = "nil"
},
setNearPlane = {
type = "method",
description = "Sets the camera's near plane distance.\n\n–> MOAICamera2D self\n[–> number near: Default value is 1.]\n<– nil",
args = "(MOAICamera2D self, [number near])",
returns = "nil"
}
}
},
MOAICameraAnchor2D = {
type = "class",
inherits = "MOAINode",
description = "Attaches fitting information to a transform. Used by MOAICameraFitter2D.",
childs = {
setParent = {
type = "method",
description = "Attach the anchor to a transform.\n\n–> MOAICameraAnchor2D self\n[–> MOAINode parent]\n<– nil",
args = "(MOAICameraAnchor2D self, [MOAINode parent])",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the dimensions (in world units) of the anchor.\n\n–> MOAICameraAnchor2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAICameraAnchor2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
}
}
},
MOAICameraFitter2D = {
type = "class",
inherits = "MOAIAction MOAINode",
description = "Action to dynamically fit a camera transform to a set of targets given a viewport and world space constraints.",
childs = {
FITTING_MODE_APPLY_ANCHORS = {
type = "value"
},
FITTING_MODE_APPLY_BOUNDS = {
type = "value"
},
FITTING_MODE_DEFAULT = {
type = "value"
},
FITTING_MODE_MASK = {
type = "value"
},
FITTING_MODE_SEEK_LOC = {
type = "value"
},
FITTING_MODE_SEEK_SCALE = {
type = "value"
},
clearAnchors = {
type = "method",
description = "Remove all camera anchors from the fitter.\n\n–> MOAICameraFitter2D self\n<– nil",
args = "MOAICameraFitter2D self",
returns = "nil"
},
clearFitMode = {
type = "method",
description = "Clears bits in the fitting mask.\n\n–> MOAICameraFitter2D self\n[–> number mask: Default value is FITTING_MODE_MASK]\n<– nil",
args = "(MOAICameraFitter2D self, [number mask])",
returns = "nil"
},
getFitDistance = {
type = "method",
description = "Returns the distance between the camera's current x, y, scale and the target x, y, scale. As the camera approaches its target, the distance approaches 0. Check the value returned by this function against a small epsilon value.\n\n–> MOAICameraFitter2D self\n<– number distance",
args = "MOAICameraFitter2D self",
returns = "number distance",
valuetype = "number"
},
getFitLoc = {
type = "method",
description = "Get the fitter location.\n\n–> MOAICameraFitter2D self\n<– number x\n<– number y",
args = "MOAICameraFitter2D self",
returns = "(number x, number y)",
valuetype = "number"
},
getFitMode = {
type = "method",
description = "Gets bits in the fitting mask.\n\n–> MOAICameraFitter2D self\n<– number mask",
args = "MOAICameraFitter2D self",
returns = "number mask",
valuetype = "number"
},
getFitScale = {
type = "method",
description = "Returns the fit scale\n\n–> MOAICameraFitter2D self\n<– number scale",
args = "MOAICameraFitter2D self",
returns = "number scale",
valuetype = "number"
},
getTargetLoc = {
type = "method",
description = "Get the target location.\n\n–> MOAICameraFitter2D self\n<– number x\n<– number y",
args = "MOAICameraFitter2D self",
returns = "(number x, number y)",
valuetype = "number"
},
getTargetScale = {
type = "method",
description = "Returns the target scale\n\n–> MOAICameraFitter2D self\n<– number scale",
args = "MOAICameraFitter2D self",
returns = "number scale",
valuetype = "number"
},
insertAnchor = {
type = "method",
description = "Add an anchor to the fitter.\n\n–> MOAICameraFitter2D self\n–> MOAICameraAnchor2D anchor\n<– nil",
args = "(MOAICameraFitter2D self, MOAICameraAnchor2D anchor)",
returns = "nil"
},
removeAnchor = {
type = "method",
description = "Remove an anchor from the fitter.\n\n–> MOAICameraFitter2D self\n–> MOAICameraAnchor2D anchor\n<– nil",
args = "(MOAICameraFitter2D self, MOAICameraAnchor2D anchor)",
returns = "nil"
},
setBounds = {
type = "method",
description = "Sets or clears the world bounds of the fitter. The camera will not move outside of the fitter's bounds.\n\nOverload:\n–> MOAICameraFitter2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil\n\nOverload:\n–> MOAICameraFitter2D self\n<– nil",
args = "(MOAICameraFitter2D self, [number xMin, number yMin, number xMax, number yMax])",
returns = "nil"
},
setCamera = {
type = "method",
description = "Set a MOAITransform for the fitter to use as a camera. The fitter will dynamically change the location and scale of the camera to keep all of the anchors on the screen.\n\n–> MOAICameraFitter2D self\n[–> MOAITransform camera: Default value is nil.]\n<– nil",
args = "(MOAICameraFitter2D self, [MOAITransform camera])",
returns = "nil"
},
setDamper = {
type = "method",
description = "Sets the fitter's damper coefficient. This is a scalar applied to the difference between the camera transform's location and the fitter's target location every frame. The smaller the coefficient, the tighter the fit will be. A value of '0' will not dampen at all; a value of '1' will never move the camera.\n\n–> MOAICameraFitter2D self\n[–> number damper: Default value is 0.]\n<– nil",
args = "(MOAICameraFitter2D self, [number damper])",
returns = "nil"
},
setFitLoc = {
type = "method",
description = "Set the fitter's location.\n\n–> MOAICameraFitter2D self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> boolean snap: Default value is false.]\n<– nil",
args = "(MOAICameraFitter2D self, [number x, [number y, [boolean snap]]])",
returns = "nil"
},
setFitMode = {
type = "method",
description = "Sets bits in the fitting mask.\n\n–> MOAICameraFitter2D self\n[–> number mask: Default value is FITTING_MODE_DEFAULT]\n<– nil",
args = "(MOAICameraFitter2D self, [number mask])",
returns = "nil"
},
setFitScale = {
type = "method",
description = "Set the fitter's scale.\n\n–> MOAICameraFitter2D self\n[–> number scale: Default value is 1.]\n[–> boolean snap: Default value is false.]\n<– nil",
args = "(MOAICameraFitter2D self, [number scale, [boolean snap]])",
returns = "nil"
},
setMin = {
type = "method",
description = "Set the minimum number of world units to be displayed by the camera along either axis.\n\n–> MOAICameraFitter2D self\n[–> number min: Default value is 0.]\n<– nil",
args = "(MOAICameraFitter2D self, [number min])",
returns = "nil"
},
setViewport = {
type = "method",
description = "Set the viewport to be used for fitting.\n\n–> MOAICameraFitter2D self\n[–> MOAIViewport viewport: Default value is nil.]\n<– nil",
args = "(MOAICameraFitter2D self, [MOAIViewport viewport])",
returns = "nil"
},
snapToTarget = {
type = "method",
description = "Snap the camera to the target fitting.\n\nOverload:\n–> MOAICameraFitter2D self\n<– nil\n\nOverload:\n–> MOAICameraFitter2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAICameraFitter2D self, [MOAITransform transform])",
returns = "nil"
}
}
},
MOAIChartBoostAndroid = {
type = "class",
inherits = "MOAILuaObject",
childs = {
hasCachedInterstitial = {
type = "function",
description = "Determine whether or not a cached interstitial is available.\n\n<– boolean hasCached",
args = "()",
returns = "boolean hasCached",
valuetype = "boolean"
},
init = {
type = "function",
description = "Initialize ChartBoost.\n\n–> string appId: Available in ChartBoost dashboard settings.\n–> string appSignature: Available in ChartBoost dashboard settings.\n<– nil",
args = "(string appId, string appSignature)",
returns = "nil"
},
loadInterstitial = {
type = "function",
description = "Request that an interstitial ad be cached for later display.\n\n[–> string locationId: Optional location ID.]\n<– nil",
args = "[string locationId]",
returns = "nil"
},
showInterstitial = {
type = "function",
description = "Request an interstitial ad display if a cached ad is available.\n\n[–> string locationId: Optional location ID.]\n<– nil",
args = "[string locationId]",
returns = "nil"
}
}
},
MOAIClearableView = {
type = "class",
inherits = "MOAILuaObject",
childs = {
setClearColor = {
type = "method",
description = "At the start of each frame the device will by default automatically render a background color. Using this function you can set the background color that is drawn each frame. If you specify no arguments to this function, then automatic redraw of the background color will be turned off (i.e. the previous render will be used as the background).\n\nOverload:\n–> MOAIClearableView self\n[–> number red: The red value of the color.]\n[–> number green: The green value of the color.]\n[–> number blue: The blue value of the color.]\n[–> number alpha: The alpha value of the color.]\n<– nil\n\nOverload:\n–> MOAIClearableView self\n–> MOAIColor color\n<– nil",
args = "(MOAIClearableView self, [(number red, [number green, [number blue, [number alpha]]]) | MOAIColor color])",
returns = "nil"
},
setClearDepth = {
type = "method",
description = "At the start of each frame the buffer will by default automatically clear the depth buffer. This function sets whether or not the depth buffer should be cleared at the start of each frame.\n\n–> MOAIClearableView self\n–> boolean clearDepth: Whether to clear the depth buffer each frame.\n<– nil",
args = "(MOAIClearableView self, boolean clearDepth)",
returns = "nil"
}
}
},
MOAIColor = {
type = "class",
inherits = "MOAINode ZLColorVec",
description = "Color vector with animation helper methods.",
childs = {
ATTR_A_COL = {
type = "value"
},
ATTR_B_COL = {
type = "value"
},
ATTR_G_COL = {
type = "value"
},
ATTR_R_COL = {
type = "value"
},
COLOR_TRAIT = {
type = "value"
},
INHERIT_COLOR = {
type = "value"
},
moveColor = {
type = "method",
description = "Animate the color by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAIColor self\n–> number rDelta: Delta to be added to r.\n–> number gDelta: Delta to be added to g.\n–> number bDelta: Delta to be added to b.\n–> number aDelta: Delta to be added to a.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAIColor self, number rDelta, number gDelta, number bDelta, number aDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekColor = {
type = "method",
description = "Animate the color by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAIColor self\n–> number rGoal: Desired resulting value for r.\n–> number gGoal: Desired resulting value for g.\n–> number bGoal: Desired resulting value for b.\n–> number aGoal: Desired resulting value for a.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAIColor self, number rGoal, number gGoal, number bGoal, number aGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
setColor = {
type = "method",
description = "Initialize the color.\n\n–> MOAIColor self\n–> number r: Default value is 0.\n–> number g: Default value is 0.\n–> number b: Default value is 0.\n[–> number a: Default value is 1.]\n<– nil",
args = "(MOAIColor self, number r, number g, number b, [number a])",
returns = "nil"
},
setParent = {
type = "method",
description = "This method has been deprecated. Use MOAINode setAttrLink instead.\n\n–> MOAIColor self\n[–> MOAINode parent: Default value is nil.]\n<– nil",
args = "(MOAIColor self, [MOAINode parent])",
returns = "nil"
}
}
},
MOAICompassSensor = {
type = "class",
inherits = "MOAISensor",
description = "Device heading sensor.",
childs = {
getHeading = {
type = "method",
description = "Returns the current heading according to the built-in compass.\n\n–> MOAICompassSensor self\n<– number heading",
args = "MOAICompassSensor self",
returns = "number heading",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the heading changes.\n\n–> MOAICompassSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAICompassSensor self, [function callback])",
returns = "nil"
}
}
},
MOAICoroutine = {
type = "class",
inherits = "MOAIAction",
description = "Binds a Lua coroutine to a MOAIAction.",
childs = {
blockOnAction = {
type = "function",
description = "Skip updating current thread until the specified action is no longer busy. A little more efficient than spinlocking from Lua.\n\n–> MOAIAction blocker\n<– nil",
args = "MOAIAction blocker",
returns = "nil"
},
currentThread = {
type = "function",
description = "Returns the currently running thread (if any).\n\n<– MOAICoroutine currentThread: Current thread or nil.",
args = "()",
returns = "MOAICoroutine currentThread",
valuetype = "MOAICoroutine"
},
run = {
type = "method",
description = "Starts a thread with a function and passes parameters to it.\n\n–> MOAICoroutine self\n–> function threadFunc\n–> ... parameters\n<– nil",
args = "(MOAICoroutine self, function threadFunc, ... parameters)",
returns = "nil"
}
}
},
MOAICp = {
type = "class",
inherits = "MOAILuaObject",
description = "Singleton for Chipmunk global configuration.",
childs = {
getBiasCoefficient = {
type = "function",
description = "Returns the current bias coefficient.\n\n<– number bias: The bias coefficient.",
args = "()",
returns = "number bias",
valuetype = "number"
},
getCollisionSlop = {
type = "function",
description = "Returns the current collision slop.\n\n<– number slop",
args = "()",
returns = "number slop",
valuetype = "number"
},
getContactPersistence = {
type = "function",
description = "Returns the current contact persistence.\n\n<– number persistence",
args = "()",
returns = "number persistence",
valuetype = "number"
},
setBiasCoefficient = {
type = "function",
description = "Sets the bias coefficient.\n\n–> number bias\n<– nil",
args = "number bias",
returns = "nil"
},
setCollisionSlop = {
type = "function",
description = "Sets the collision slop.\n\n–> number slop\n<– nil",
args = "number slop",
returns = "nil"
},
setContactPersistence = {
type = "function",
description = "Sets the contact persistance.\n\n–> number persistance\n<– nil",
args = "number persistance",
returns = "nil"
}
}
},
MOAICpArbiter = {
type = "class",
inherits = "MOAILuaObject",
description = "Chipmunk Arbiter.",
childs = {
countContacts = {
type = "method",
description = "Returns the number of contacts occurring with this arbiter.\n\n–> MOAICpArbiter self\n<– number count: The number of contacts occurring.",
args = "MOAICpArbiter self",
returns = "number count",
valuetype = "number"
},
getContactDepth = {
type = "method",
description = "Returns the depth of a contact point between two objects.\n\n–> MOAICpArbiter self\n–> number id: The ID of the contact.\n<– number depth: The depth of the contact in pixels (i.e. how far it overlaps).",
args = "(MOAICpArbiter self, number id)",
returns = "number depth",
valuetype = "number"
},
getContactNormal = {
type = "method",
description = "Returns the normal of a contact point between two objects.\n\n–> MOAICpArbiter self\n–> number id: The ID of the contact.\n<– boolean x: The X component of the normal vector.\n<– boolean y: The Y component of the normal vector.",
args = "(MOAICpArbiter self, number id)",
returns = "(boolean x, boolean y)",
valuetype = "boolean"
},
getContactPoint = {
type = "method",
description = "Returns the position of a contact point between two objects.\n\n–> MOAICpArbiter self\n–> number id: The ID of the contact.\n<– boolean x: The X component of the position vector.\n<– boolean y: The Y component of the position vector.",
args = "(MOAICpArbiter self, number id)",
returns = "(boolean x, boolean y)",
valuetype = "boolean"
},
getTotalImpulse = {
type = "method",
description = "Returns the total impulse of a contact point between two objects.\n\n–> MOAICpArbiter self\n<– boolean x: The X component of the force involved in the contact.\n<– boolean y: The Y component of the force involved in the contact.",
args = "MOAICpArbiter self",
returns = "(boolean x, boolean y)",
valuetype = "boolean"
},
getTotalImpulseWithFriction = {
type = "method",
description = "Returns the total impulse of a contact point between two objects, also including frictional forces.\n\n–> MOAICpArbiter self\n<– boolean x: The X component of the force involved in the contact.\n<– boolean y: The Y component of the force involved in the contact.",
args = "MOAICpArbiter self",
returns = "(boolean x, boolean y)",
valuetype = "boolean"
},
isFirstContact = {
type = "method",
description = "Returns whether this is the first time that these two objects have contacted.\n\n–> MOAICpArbiter self\n<– boolean first: Whether this is the first instance of a collision.",
args = "MOAICpArbiter self",
returns = "boolean first",
valuetype = "boolean"
}
}
},
MOAICpBody = {
type = "class",
inherits = "MOAITransformBase MOAICpPrim",
description = "Chipmunk Body.",
childs = {
NONE = {
type = "value"
},
REMOVE_BODY = {
type = "value"
},
REMOVE_BODY_AND_SHAPES = {
type = "value"
},
activate = {
type = "method",
description = "Activates a body after it has been put to sleep (physics will now be processed for this body again).\n\n–> MOAICpBody self\n<– nil",
args = "MOAICpBody self",
returns = "nil"
},
addCircle = {
type = "method",
description = "Adds a circle to the body.\n\n–> MOAICpBody self\n–> number radius\n–> number x\n–> number y\n<– MOAICpShape circle",
args = "(MOAICpBody self, number radius, number x, number y)",
returns = "MOAICpShape circle",
valuetype = "MOAICpShape"
},
addPolygon = {
type = "method",
description = "Adds a polygon to the body.\n\n–> MOAICpBody self\n–> table polygon\n<– MOAICpShape polygon",
args = "(MOAICpBody self, table polygon)",
returns = "MOAICpShape polygon",
valuetype = "MOAICpShape"
},
addRect = {
type = "method",
description = "Adds a rectangle to the body.\n\n–> MOAICpBody self\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n<– MOAICpShape rectangle",
args = "(MOAICpBody self, number x1, number y1, number x2, number y2)",
returns = "MOAICpShape rectangle",
valuetype = "MOAICpShape"
},
addSegment = {
type = "method",
description = "Adds a segment to the body.\n\n–> MOAICpBody self\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n[–> number radius]\n<– MOAICpShape segment",
args = "(MOAICpBody self, number x1, number y1, number x2, number y2, [number radius])",
returns = "MOAICpShape segment",
valuetype = "MOAICpShape"
},
applyForce = {
type = "method",
description = "Applies force to the body, taking into account any existing forces being applied.\n\n–> MOAICpBody self\n–> number fx\n–> number fy\n–> number rx\n–> number ry\n<– nil",
args = "(MOAICpBody self, number fx, number fy, number rx, number ry)",
returns = "nil"
},
applyImpulse = {
type = "method",
description = "Applies impulse to the body, taking into account any existing impulses being applied.\n\n–> MOAICpBody self\n–> number jx\n–> number jy\n–> number rx\n–> number ry\n<– nil",
args = "(MOAICpBody self, number jx, number jy, number rx, number ry)",
returns = "nil"
},
getAngle = {
type = "method",
description = "Returns the angle of the body.\n\n–> MOAICpBody self\n<– number angle: The current angle.",
args = "MOAICpBody self",
returns = "number angle",
valuetype = "number"
},
getAngVel = {
type = "method",
description = "Returns the angular velocity of the body.\n\n–> MOAICpBody self\n<– number angle: The current angular velocity.",
args = "MOAICpBody self",
returns = "number angle",
valuetype = "number"
},
getForce = {
type = "method",
description = "Returns the force of the body.\n\n–> MOAICpBody self\n<– number x: The X component of the current force being applied.\n<– number y: The Y component of the current force being applied.",
args = "MOAICpBody self",
returns = "(number x, number y)",
valuetype = "number"
},
getMass = {
type = "method",
description = "Returns the mass of the body.\n\n–> MOAICpBody self\n<– number mass: The current mass.",
args = "MOAICpBody self",
returns = "number mass",
valuetype = "number"
},
getMoment = {
type = "method",
description = "Returns the moment of the body.\n\n–> MOAICpBody self\n<– number moment: The current moment.",
args = "MOAICpBody self",
returns = "number moment",
valuetype = "number"
},
getPos = {
type = "method",
description = "Returns the position of the body.\n\n–> MOAICpBody self\n<– number x: The X position.\n<– number y: The Y position.",
args = "MOAICpBody self",
returns = "(number x, number y)",
valuetype = "number"
},
getRot = {
type = "method",
description = "Returns the rotation of the body.\n\n–> MOAICpBody self\n<– number x: The X position.\n<– number y: The Y position.",
args = "MOAICpBody self",
returns = "(number x, number y)",
valuetype = "number"
},
getTorque = {
type = "method",
description = "Returns the torque of the body.\n\n–> MOAICpBody self\n<– number torque: The current torque.",
args = "MOAICpBody self",
returns = "number torque",
valuetype = "number"
},
getVel = {
type = "method",
description = "Returns the velocity of the body.\n\n–> MOAICpBody self\n<– number x: The X component of the current velocity.\n<– number y: The Y component of the current velocity.",
args = "MOAICpBody self",
returns = "(number x, number y)",
valuetype = "number"
},
isRogue = {
type = "method",
description = "Returns whether the body is not yet currently associated with a space.\n\n–> MOAICpBody self\n<– boolean static: Whether the body is not associated with a space.",
args = "MOAICpBody self",
returns = "boolean static",
valuetype = "boolean"
},
isSleeping = {
type = "method",
description = "Returns whether the body is currently sleeping.\n\n–> MOAICpBody self\n<– boolean sleeping: Whether the body is sleeping.",
args = "MOAICpBody self",
returns = "boolean sleeping",
valuetype = "boolean"
},
isStatic = {
type = "method",
description = "Returns whether the body is static.\n\n–> MOAICpBody self\n<– boolean static: Whether the body static.",
args = "MOAICpBody self",
returns = "boolean static",
valuetype = "boolean"
},
localToWorld = {
type = "method",
description = "Converts the relative position to an absolute position based on position of the object being (0, 0) for the relative position.\n\n–> MOAICpBody self\n–> number rx: The relative X position.\n–> number ry: The relative Y position.\n<– number ax: The absolute X position.\n<– number ay: The absolute Y position.",
args = "(MOAICpBody self, number rx, number ry)",
returns = "(number ax, number ay)",
valuetype = "number"
},
new = {
type = "function",
description = "Creates a new body with the specified mass and moment.\n\n–> number m: The mass of the new body.\n–> number i: The moment of the new body.\n<– MOAICpBody body: The new body.",
args = "(number m, number i)",
returns = "MOAICpBody body",
valuetype = "MOAICpBody"
},
newStatic = {
type = "function",
description = "Creates a new static body.\n\n<– MOAICpBody body: The new static body.",
args = "()",
returns = "MOAICpBody body",
valuetype = "MOAICpBody"
},
resetForces = {
type = "method",
description = "Resets all forces on the body.\n\n–> MOAICpBody self\n<– nil",
args = "MOAICpBody self",
returns = "nil"
},
setAngle = {
type = "method",
description = "Sets the angle of the body.\n\n–> MOAICpBody self\n–> number angle: The angle of the body.\n<– nil",
args = "(MOAICpBody self, number angle)",
returns = "nil"
},
setAngVel = {
type = "method",
description = "Sets the angular velocity of the body.\n\n–> MOAICpBody self\n–> number angvel: The angular velocity of the body.\n<– nil",
args = "(MOAICpBody self, number angvel)",
returns = "nil"
},
setForce = {
type = "method",
description = "Sets the force on the body.\n\n–> MOAICpBody self\n–> number forcex: The X force being applied to the body.\n–> number forcey: The Y force being applied to the body.\n<– nil",
args = "(MOAICpBody self, number forcex, number forcey)",
returns = "nil"
},
setMass = {
type = "method",
description = "Sets the mass of the body.\n\n–> MOAICpBody self\n–> number mass: The mass of the body.\n<– nil",
args = "(MOAICpBody self, number mass)",
returns = "nil"
},
setMoment = {
type = "method",
description = "Sets the moment of the body.\n\n–> MOAICpBody self\n–> number moment: The moment of the body.\n<– nil",
args = "(MOAICpBody self, number moment)",
returns = "nil"
},
setPos = {
type = "method",
description = "Sets the position of the body.\n\n–> MOAICpBody self\n–> number x: The X position of the body.\n–> number y: The Y position of the body.\n<– nil",
args = "(MOAICpBody self, number x, number y)",
returns = "nil"
},
setRemoveFlag = {
type = "method",
description = "Sets the removal flag on the body.\n\n–> MOAICpBody self\n–> number flag: The removal flag.\n<– nil",
args = "(MOAICpBody self, number flag)",
returns = "nil"
},
setTorque = {
type = "method",
description = "Sets the torque of the body.\n\n–> MOAICpBody self\n–> number torque: The torque of the body.\n<– nil",
args = "(MOAICpBody self, number torque)",
returns = "nil"
},
setVel = {
type = "method",
description = "Sets the velocity of the body.\n\n–> MOAICpBody self\n–> number x: The horizontal velocity.\n–> number y: The vertical velocity.\n<– nil",
args = "(MOAICpBody self, number x, number y)",
returns = "nil"
},
sleep = {
type = "method",
description = "Puts the body to sleep (physics will no longer be processed for it until it is activated).\n\n–> MOAICpBody self\n<– nil",
args = "MOAICpBody self",
returns = "nil"
},
sleepWithGroup = {
type = "method",
description = "Forces an object to sleep. Pass in another sleeping body to add the object to the sleeping body's existing group.\n\n–> MOAICpBody self\n–> MOAICpBody group\n<– nil",
args = "(MOAICpBody self, MOAICpBody group)",
returns = "nil"
},
worldToLocal = {
type = "method",
description = "Converts the absolute position to a relative position based on position of the object being (0, 0) for the relative position.\n\n–> MOAICpBody self\n–> number ax: The absolute X position.\n–> number ay: The absolute Y position.\n<– number rx: The relative X position.\n<– number ry: The relative Y position.",
args = "(MOAICpBody self, number ax, number ay)",
returns = "(number rx, number ry)",
valuetype = "number"
}
}
},
MOAICpConstraint = {
type = "class",
inherits = "MOAILuaObject MOAICpPrim",
description = "Chipmunk Constraint.",
childs = {
getBiasCoef = {
type = "method",
description = "Returns the current bias coefficient.\n\n–> MOAICpConstraint self\n<– number bias: The bias coefficient.",
args = "MOAICpConstraint self",
returns = "number bias",
valuetype = "number"
},
getMaxBias = {
type = "method",
description = "Returns the maximum bias coefficient.\n\n–> MOAICpConstraint self\n<– number bias: The maximum bias coefficient.",
args = "MOAICpConstraint self",
returns = "number bias",
valuetype = "number"
},
getMaxForce = {
type = "method",
description = "Returns the maximum force allowed.\n\n–> MOAICpConstraint self\n<– number bias: The maximum force allowed.",
args = "MOAICpConstraint self",
returns = "number bias",
valuetype = "number"
},
newDampedRotarySpring = {
type = "function",
description = "Creates a new damped rotary string between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number restAngle: The angle at which the spring is at rest.\n–> number stiffness: The stiffness of the spring.\n–> number damping: The damping applied to the spring.\n<– MOAICpConstraint spring: The new spring.",
args = "(MOAICpBody first, MOAICpBody second, number restAngle, number stiffness, number damping)",
returns = "MOAICpConstraint spring",
valuetype = "MOAICpConstraint"
},
newDampedSpring = {
type = "function",
description = "Creates a new damped string between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number x1: The X position of the first anchor.\n–> number y1: The Y position of the first anchor.\n–> number x2: The X position of the second anchor.\n–> number y2: The Y position of the second anchor.\n–> number restAngle: The angle at which the spring is at rest.\n–> number stiffness: The stiffness of the spring.\n–> number damping: The damping applied to the spring.\n<– MOAICpConstraint spring: The new spring.",
args = "(MOAICpBody first, MOAICpBody second, number x1, number y1, number x2, number y2, number restAngle, number stiffness, number damping)",
returns = "MOAICpConstraint spring",
valuetype = "MOAICpConstraint"
},
newGearJoint = {
type = "function",
description = "Creates a new gear joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number phase: The phase of the gear.\n–> number ratio: The gear ratio.\n<– MOAICpConstraint gear: The new gear joint.",
args = "(MOAICpBody first, MOAICpBody second, number phase, number ratio)",
returns = "MOAICpConstraint gear",
valuetype = "MOAICpConstraint"
},
newGrooveJoint = {
type = "function",
description = "Creates a new groove joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number gx1\n–> number gy1\n–> number gx2\n–> number gy2\n–> number ax\n–> number ay\n<– MOAICpConstraint groove: The new groove joint.",
args = "(MOAICpBody first, MOAICpBody second, number gx1, number gy1, number gx2, number gy2, number ax, number ay)",
returns = "MOAICpConstraint groove",
valuetype = "MOAICpConstraint"
},
newPinJoint = {
type = "function",
description = "Creates a new pin joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number ax1\n–> number ay1\n–> number ax2\n–> number ay2\n<– MOAICpConstraint pin: The new pin joint.",
args = "(MOAICpBody first, MOAICpBody second, number ax1, number ay1, number ax2, number ay2)",
returns = "MOAICpConstraint pin",
valuetype = "MOAICpConstraint"
},
newPivotJoint = {
type = "function",
description = "Creates a new pivot joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number x\n–> number y\n[–> number ax]\n[–> number ay]\n<– MOAICpConstraint pivot: The new pivot joint.",
args = "(MOAICpBody first, MOAICpBody second, number x, number y, [number ax, [number ay]])",
returns = "MOAICpConstraint pivot",
valuetype = "MOAICpConstraint"
},
newRatchetJoint = {
type = "function",
description = "Creates a new ratchet joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number phase: The phase of the gear.\n–> number ratchet: The ratchet value.\n<– MOAICpConstraint ratchet: The new pivot joint.",
args = "(MOAICpBody first, MOAICpBody second, number phase, number ratchet)",
returns = "MOAICpConstraint ratchet",
valuetype = "MOAICpConstraint"
},
newRotaryLimitJoint = {
type = "function",
description = "Creates a new rotary limit joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number min: The minimum rotary value.\n–> number max: The maximum rotary value.\n<– MOAICpConstraint limit: The new rotary limit joint.",
args = "(MOAICpBody first, MOAICpBody second, number min, number max)",
returns = "MOAICpConstraint limit",
valuetype = "MOAICpConstraint"
},
newSimpleMotor = {
type = "function",
description = "Creates a new simple motor joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number rate: The rotation rate of the simple motor.\n<– MOAICpConstraint motor: The new simple motor joint.",
args = "(MOAICpBody first, MOAICpBody second, number rate)",
returns = "MOAICpConstraint motor",
valuetype = "MOAICpConstraint"
},
newSlideJoint = {
type = "function",
description = "Creates a new slide joint between the two specified bodies.\n\n–> MOAICpBody first\n–> MOAICpBody second\n–> number ax1\n–> number ay1\n–> number ax2\n–> number ay2\n–> number min\n–> number max\n<– MOAICpConstraint motor: The new slide joint.",
args = "(MOAICpBody first, MOAICpBody second, number ax1, number ay1, number ax2, number ay2, number min, number max)",
returns = "MOAICpConstraint motor",
valuetype = "MOAICpConstraint"
},
setBiasCoef = {
type = "method",
description = "Sets the current bias coefficient.\n\n–> MOAICpConstraint self\n–> number bias: The bias coefficient.\n<– nil",
args = "(MOAICpConstraint self, number bias)",
returns = "nil"
},
setMaxBias = {
type = "method",
description = "Sets the maximum bias coefficient.\n\n–> MOAICpConstraint self\n–> number bias: The maximum bias coefficient.\n<– nil",
args = "(MOAICpConstraint self, number bias)",
returns = "nil"
},
setMaxForce = {
type = "method",
description = "Sets the maximum force allowed.\n\n–> MOAICpConstraint self\n–> number bias: The maximum force allowed.\n<– nil",
args = "(MOAICpConstraint self, number bias)",
returns = "nil"
}
}
},
MOAICpPrim = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAICpShape = {
type = "class",
inherits = "MOAILuaObject MOAICpPrim",
description = "Chipmunk Shape.",
childs = {
areaForCircle = {
type = "function",
description = "Returns the area for a ring or circle.\n\nOverload:\n–> number radius\n<– number area\n\nOverload:\n–> number innerRadius\n–> number outerRadius\n<– number area",
args = "(number radius | (number innerRadius, number outerRadius))",
returns = "number area",
valuetype = "number"
},
areaForPolygon = {
type = "function",
description = "Returns the area for a polygon.\n\n–> table vertices: Array containing vertex coordinate components ( t[1] = x0, t[2] = y0, t[3] = x1, t[4] = y1... )\n<– number area",
args = "table vertices",
returns = "number area",
valuetype = "number"
},
areaForRect = {
type = "function",
description = "Returns the area for the specified rectangle.\n\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n<– number area: The calculated area.",
args = "(number x1, number y1, number x2, number y2)",
returns = "number area",
valuetype = "number"
},
areaForSegment = {
type = "function",
description = "Returns the area for the specified segment.\n\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number r\n<– number area: The calculated area.",
args = "(number x1, number y1, number x2, number y2, number r)",
returns = "number area",
valuetype = "number"
},
getBody = {
type = "method",
description = "Returns the current body for the shape.\n\n–> MOAICpShape self\n<– MOAICpBody body: The body.",
args = "MOAICpShape self",
returns = "MOAICpBody body",
valuetype = "MOAICpBody"
},
getElasticity = {
type = "method",
description = "Returns the current elasticity.\n\n–> MOAICpShape self\n<– number elasticity: The elasticity.",
args = "MOAICpShape self",
returns = "number elasticity",
valuetype = "number"
},
getFriction = {
type = "method",
description = "Returns the current friction.\n\n–> MOAICpShape self\n<– number friction: The friction.",
args = "MOAICpShape self",
returns = "number friction",
valuetype = "number"
},
getGroup = {
type = "method",
description = "Returns the current group ID.\n\n–> MOAICpShape self\n<– number group: The group ID.",
args = "MOAICpShape self",
returns = "number group",
valuetype = "number"
},
getLayers = {
type = "method",
description = "Returns the current layer ID.\n\n–> MOAICpShape self\n<– number layer: The layer ID.",
args = "MOAICpShape self",
returns = "number layer",
valuetype = "number"
},
getSurfaceVel = {
type = "method",
description = "Returns the current surface velocity?\n\n–> MOAICpShape self\n<– number x: The X component of the surface velocity.\n<– number y: The Y component of the surface velocity.",
args = "MOAICpShape self",
returns = "(number x, number y)",
valuetype = "number"
},
getType = {
type = "method",
description = "Returns the current collision type.\n\n–> MOAICpShape self\n<– number type: The collision type.",
args = "MOAICpShape self",
returns = "number type",
valuetype = "number"
},
inside = {
type = "method",
description = "Returns whether the specified point is inside the shape.\n\n–> MOAICpShape self\n–> number x\n–> number y\n<– boolean inside: Whether the point is inside the shape.",
args = "(MOAICpShape self, number x, number y)",
returns = "boolean inside",
valuetype = "boolean"
},
isSensor = {
type = "method",
description = "Returns whether the current shape is a sensor.\n\n–> MOAICpShape self\n<– boolean sensor: Whether the shape is a sensor.",
args = "MOAICpShape self",
returns = "boolean sensor",
valuetype = "boolean"
},
momentForCircle = {
type = "function",
description = "Return the moment of inertia for the circle.\n\n–> number m\n–> number r1\n–> number r2\n–> number ox\n–> number oy\n<– number moment",
args = "(number m, number r1, number r2, number ox, number oy)",
returns = "number moment",
valuetype = "number"
},
momentForPolygon = {
type = "function",
description = "Returns the moment of intertia for the polygon.\n\n–> number m\n–> table polygon\n<– number moment",
args = "(number m, table polygon)",
returns = "number moment",
valuetype = "number"
},
momentForRect = {
type = "function",
description = "Returns the moment of intertia for the rect.\n\n–> number m\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n<– number moment",
args = "(number m, number x1, number y1, number x2, number y2)",
returns = "number moment",
valuetype = "number"
},
momentForSegment = {
type = "function",
description = "Returns the moment of intertia for the segment.\n\n–> number m\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n<– number moment",
args = "(number m, number x1, number y1, number x2, number y2)",
returns = "number moment",
valuetype = "number"
},
setElasticity = {
type = "method",
description = "Sets the current elasticity.\n\n–> MOAICpShape self\n–> number elasticity: The elasticity.\n<– nil",
args = "(MOAICpShape self, number elasticity)",
returns = "nil"
},
setFriction = {
type = "method",
description = "Sets the current friction.\n\n–> MOAICpShape self\n–> number friction: The friction.\n<– nil",
args = "(MOAICpShape self, number friction)",
returns = "nil"
},
setGroup = {
type = "method",
description = "Sets the current group ID.\n\n–> MOAICpShape self\n–> number group: The group ID.\n<– nil",
args = "(MOAICpShape self, number group)",
returns = "nil"
},
setIsSensor = {
type = "method",
description = "Sets whether this shape is a sensor.\n\n–> MOAICpShape self\n–> boolean sensor: Whether this shape is a sensor.\n<– nil",
args = "(MOAICpShape self, boolean sensor)",
returns = "nil"
},
setLayers = {
type = "method",
description = "Sets the current layer ID.\n\n–> MOAICpShape self\n–> number layer: The layer ID.\n<– nil",
args = "(MOAICpShape self, number layer)",
returns = "nil"
},
setSurfaceVel = {
type = "method",
description = "Sets the current surface velocity.\n\n–> MOAICpShape self\n–> number x: The X component of the surface velocity.\n–> number y: The Y component of the surface velocity.\n<– nil",
args = "(MOAICpShape self, number x, number y)",
returns = "nil"
},
setType = {
type = "method",
description = "Sets the current collision type.\n\n–> MOAICpShape self\n–> number type: The collision type.\n<– nil",
args = "(MOAICpShape self, number type)",
returns = "nil"
}
}
},
MOAICpSpace = {
type = "class",
inherits = "MOAIAction",
description = "Chipmunk Space.",
childs = {
ALL = {
type = "value"
},
BEGIN = {
type = "value"
},
POST_SOLVE = {
type = "value"
},
PRE_SOLVE = {
type = "value"
},
SEPARATE = {
type = "value"
},
activateShapesTouchingShape = {
type = "method",
description = "Activates shapes that are currently touching the specified shape.\n\n–> MOAICpSpace self\n–> MOAICpShape shape\n<– nil",
args = "(MOAICpSpace self, MOAICpShape shape)",
returns = "nil"
},
getDamping = {
type = "method",
description = "Returns the current damping in the space.\n\n–> MOAICpSpace self\n<– number damping",
args = "MOAICpSpace self",
returns = "number damping",
valuetype = "number"
},
getGravity = {
type = "method",
description = "Returns the current gravity as two return values (x grav, y grav).\n\n–> MOAICpSpace self\n<– number xGrav\n<– number yGrav",
args = "MOAICpSpace self",
returns = "(number xGrav, number yGrav)",
valuetype = "number"
},
getIdleSpeedThreshold = {
type = "method",
description = "Returns the speed threshold which indicates whether a body is idle (less than or equal to threshold) or in motion (greater than threshold).\n\n–> MOAICpSpace self\n<– number idleThreshold",
args = "MOAICpSpace self",
returns = "number idleThreshold",
valuetype = "number"
},
getIterations = {
type = "method",
description = "Returns the number of iterations the space is configured to perform.\n\n–> MOAICpSpace self\n<– number iterations",
args = "MOAICpSpace self",
returns = "number iterations",
valuetype = "number"
},
getSleepTimeThreshold = {
type = "method",
description = "Returns the sleep time threshold.\n\n–> MOAICpSpace self\n<– number sleepTimeThreshold",
args = "MOAICpSpace self",
returns = "number sleepTimeThreshold",
valuetype = "number"
},
getStaticBody = {
type = "method",
description = "Returns the static body associated with this space.\n\n–> MOAICpSpace self\n<– MOAICpBody staticBody",
args = "MOAICpSpace self",
returns = "MOAICpBody staticBody",
valuetype = "MOAICpBody"
},
insertPrim = {
type = "method",
description = "Inserts a new prim into the world (can be used as a body, joint, etc.)\n\n–> MOAICpSpace self\n–> MOAICpPrim prim\n<– nil",
args = "(MOAICpSpace self, MOAICpPrim prim)",
returns = "nil"
},
rehashShape = {
type = "method",
description = "Updates the shape in the spatial hash.\n\n–> MOAICpSpace self\n–> MOAICpShape shape\n<– nil",
args = "(MOAICpSpace self, MOAICpShape shape)",
returns = "nil"
},
rehashStatic = {
type = "method",
description = "Updates the static shapes in the spatial hash.\n\n–> MOAICpSpace self\n<– nil",
args = "MOAICpSpace self",
returns = "nil"
},
removePrim = {
type = "method",
description = "Removes a prim (body, joint, etc.) from the space.\n\n–> MOAICpSpace self\n–> MOAICpPrim prim\n<– nil",
args = "(MOAICpSpace self, MOAICpPrim prim)",
returns = "nil"
},
resizeActiveHash = {
type = "method",
description = "Sets the dimensions of the active object hash.\n\n–> MOAICpSpace self\n–> number dim\n–> number count\n<– nil",
args = "(MOAICpSpace self, number dim, number count)",
returns = "nil"
},
resizeStaticHash = {
type = "method",
description = "Sets the dimensions of the static object hash.\n\n–> MOAICpSpace self\n–> number dim\n–> number count\n<– nil",
args = "(MOAICpSpace self, number dim, number count)",
returns = "nil"
},
setCollisionHandler = {
type = "method",
description = "Sets a function to handle the specific collision type on this object. If nil is passed as the handler, the collision handler is unset.\n\n–> MOAICpSpace self\n–> number collisionTypeA\n–> number collisionTypeB\n–> number mask\n–> function handler\n<– nil",
args = "(MOAICpSpace self, number collisionTypeA, number collisionTypeB, number mask, function handler)",
returns = "nil"
},
setDamping = {
type = "method",
description = "Sets the current damping in the space.\n\n–> MOAICpSpace self\n–> number damping\n<– nil",
args = "(MOAICpSpace self, number damping)",
returns = "nil"
},
setGravity = {
type = "method",
description = "Sets the current gravity in the space.\n\n–> MOAICpSpace self\n–> number xGrav\n–> number yGrav\n<– nil",
args = "(MOAICpSpace self, number xGrav, number yGrav)",
returns = "nil"
},
setIdleSpeedThreshold = {
type = "method",
description = "Sets the speed threshold which indicates whether a body is idle (less than or equal to threshold) or in motion (greater than threshold).\n\n–> MOAICpSpace self\n–> number threshold\n<– nil",
args = "(MOAICpSpace self, number threshold)",
returns = "nil"
},
setIterations = {
type = "method",
description = "Sets the number of iterations performed each simulation step.\n\n–> MOAICpSpace self\n–> number iterations\n<– nil",
args = "(MOAICpSpace self, number iterations)",
returns = "nil"
},
setSleepTimeThreshold = {
type = "method",
description = "Sets the sleep time threshold. This is the amount of time it takes bodies at rest to fall asleep.\n\n–> MOAICpSpace self\n–> number threshold\n<– nil",
args = "(MOAICpSpace self, number threshold)",
returns = "nil"
},
shapeForPoint = {
type = "method",
description = "Retrieves a shape located at the specified X and Y position, that exists on the specified layer (or any layer if nil) and is part of the specified group (or any group if nil).\n\n–> MOAICpSpace self\n–> number x\n–> number y\n[–> number layers]\n[–> number group]\n<– MOAICpShape shape",
args = "(MOAICpSpace self, number x, number y, [number layers, [number group]])",
returns = "MOAICpShape shape",
valuetype = "MOAICpShape"
},
shapeForSegment = {
type = "method",
description = "Retrieves a shape that crosses the segment specified, that exists on the specified layer (or any layer if nil) and is part of the specified group (or any group if nil).\n\n–> MOAICpSpace self\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n[–> number layers]\n[–> number group]\n<– MOAICpShape shape",
args = "(MOAICpSpace self, number x1, number y1, number x2, number y2, [number layers, [number group]])",
returns = "MOAICpShape shape",
valuetype = "MOAICpShape"
},
shapeListForPoint = {
type = "method",
description = "Retrieves a list of shapes that overlap the point specified, that exists on the specified layer (or any layer if nil) and is part of the specified group (or any group if nil).\n\n–> MOAICpSpace self\n–> number x\n–> number y\n[–> number layers]\n[–> number group]\n<– MOAICpShape shapes: The shapes that were matched as multiple return values.",
args = "(MOAICpSpace self, number x, number y, [number layers, [number group]])",
returns = "MOAICpShape shapes",
valuetype = "MOAICpShape"
},
shapeListForRect = {
type = "method",
description = "Retrieves a list of shapes that overlap the rect specified, that exists on the specified layer (or any layer if nil) and is part of the specified group (or any group if nil).\n\n–> MOAICpSpace self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n[–> number layers]\n[–> number group]\n<– MOAICpShape shapes: The shapes that were matched as multiple return values.",
args = "(MOAICpSpace self, number xMin, number yMin, number xMax, number yMax, [number layers, [number group]])",
returns = "MOAICpShape shapes",
valuetype = "MOAICpShape"
},
shapeListForSegment = {
type = "method",
description = "Retrieves a list of shapes that overlap the segment specified, that exists on the specified layer (or any layer if nil) and is part of the specified group (or any group if nil).\n\n–> MOAICpSpace self\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n[–> number layers]\n[–> number group]\n<– MOAICpShape shapes: The shapes that were matched as multiple return values.",
args = "(MOAICpSpace self, number x1, number y1, number x2, number y2, [number layers, [number group]])",
returns = "MOAICpShape shapes",
valuetype = "MOAICpShape"
}
}
},
MOAICrittercismAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Crittercism integration on Android devices. Crittercism provides real-time, actionable crash reports for mobile apps. Exposed to Lua via MOAICrittercism on all mobile platforms.",
childs = {
forceException = {
type = "function",
description = "Force and exception to send breadcrumbs to crittercism\n\n<– nil",
args = "()",
returns = "nil"
},
init = {
type = "function",
description = "Initialize Crittercism.\n\n–> string appId: Available in Crittercism dashboard settings.\n<– nil",
args = "string appId",
returns = "nil"
},
leaveBreadcrumb = {
type = "function",
description = "Leave a breadcrumb (log statement) to trace execution.\n\n–> string breadcrumb: A string describing the code location.\n<– nil",
args = "string breadcrumb",
returns = "nil"
},
setUser = {
type = "function",
description = "Sets an identifier for a user\n\n–> string identifier: A string identifying the user.\n<– nil",
args = "string identifier",
returns = "nil"
}
}
},
MOAICrittercismIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Crittercism integration on iOS devices. Crittercism provides real-time, actionable crash reports for mobile apps. Exposed to Lua via MOAICrittercism on all mobile platforms.",
childs = {}
},
MOAIDataBuffer = {
type = "class",
inherits = "MOAILuaObject",
description = "Buffer for loading and holding data. Data operations may be performed without additional penalty of marshalling buffers between Lua and C.",
childs = {
base64Decode = {
type = "method",
description = "If a string is provided, decodes it as a base64 encoded string. Otherwise, decodes the current data stored in this object as a base64 encoded sequence of characters.\n\n[–> MOAIDataBuffer self]\n[–> string data: The string data to decode. You must either provide either a MOAIDataBuffer (via a :base64Decode type call) or string data (via a .base64Decode type call), but not both.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be decoded. Otherwise the decoding occurs inline on the existing data buffer in this object, and nil is returned.",
args = "[MOAIDataBuffer self, [string data]]",
returns = "string output",
valuetype = "string"
},
base64Encode = {
type = "method",
description = "If a string is provided, encodes it in base64. Otherwise, encodes the current data stored in this object as a base64 encoded sequence of characters.\n\n[–> MOAIDataBuffer self]\n[–> string data: The string data to encode. You must either provide either a MOAIDataBuffer (via a :base64Encode type call) or string data (via a .base64Encode type call), but not both.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be encoded. Otherwise the encoding occurs inline on the existing data buffer in this object, and nil is returned.",
args = "[MOAIDataBuffer self, [string data]]",
returns = "string output",
valuetype = "string"
},
deflate = {
type = "function",
description = "Compresses the string or the current data stored in this object using the DEFLATE algorithm.\n\nOverload:\n–> string data: The string data to deflate.\n[–> number level: The level used in the DEFLATE algorithm.]\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be compressed. Otherwise the compression occurs inline on the existing data buffer in this object, and nil is returned.\n\nOverload:\n–> MOAIDataBuffer self\n[–> number level: The level used in the DEFLATE algorithm.]\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be compressed. Otherwise the compression occurs inline on the existing data buffer in this object, and nil is returned.",
args = "((string data | MOAIDataBuffer self), [number level, [number windowBits]])",
returns = "string output",
valuetype = "string"
},
getSize = {
type = "method",
description = "Returns the number of bytes in this data buffer object.\n\n–> MOAIDataBuffer self\n<– number size: The number of bytes in this data buffer object.",
args = "MOAIDataBuffer self",
returns = "number size",
valuetype = "number"
},
getString = {
type = "method",
description = "Returns the contents of the data buffer object as a string value.\n\n–> MOAIDataBuffer self\n<– string data: The data buffer object as a string.",
args = "MOAIDataBuffer self",
returns = "string data",
valuetype = "string"
},
hexDecode = {
type = "method",
description = "If a string is provided, decodes it as a hex encoded string. Otherwise, decodes the current data stored in this object as a hex encoded sequence of bytes.\n\n[–> MOAIDataBuffer self]\n[–> string data: The string data to decode. You must either provide either a MOAIDataBuffer (via a :hexDecode type call) or string data (via a .hexDecode type call), but not both.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be decoded. Otherwise the decoding occurs inline on the existing data buffer in this object, and nil is returned.",
args = "[MOAIDataBuffer self, [string data]]",
returns = "string output",
valuetype = "string"
},
hexEncode = {
type = "method",
description = "If a string is provided, encodes it in hex. Otherwise, encodes the current data stored in this object as a hex encoded sequence of characters.\n\n[–> MOAIDataBuffer self]\n[–> string data: The string data to encode. You must either provide either a MOAIDataBuffer (via a :hexEncode type call) or string data (via a .hexEncode type call), but not both.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be encoded. Otherwise the encoding occurs inline on the existing data buffer in this object, and nil is returned.",
args = "[MOAIDataBuffer self, [string data]]",
returns = "string output",
valuetype = "string"
},
inflate = {
type = "function",
description = "Decompresses the string or the current data stored in this object using the DEFLATE algorithm.\n\nOverload:\n–> string data: The string data to inflate.\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be decompressed. Otherwise the decompression occurs inline on the existing data buffer in this object, and nil is returned.\n\nOverload:\n–> MOAIDataBuffer self\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– string output: If passed a string, returns either a string or nil depending on whether it could be decompressed. Otherwise the decompression occurs inline on the existing data buffer in this object, and nil is returned.",
valuetype = "string"
},
load = {
type = "method",
description = "Copies the data from the given file into this object. This method is a synchronous operation and will block until the file is loaded.\n\n–> MOAIDataBuffer self\n–> string filename: The path to the file that the data should be loaded from.\n[–> number detectZip: One of MOAIDataBuffer.NO_UNZIP, MOAIDataBuffer.NO_UNZIP, MOAIDataBuffer.NO_UNZIP]\n[–> number windowBits: The window bits used in the DEFLATE algorithm. Pass nil to use the default value.]\n<– boolean success: Whether the file could be loaded into the object.",
args = "(MOAIDataBuffer self, string filename, [number detectZip, [number windowBits]])",
returns = "boolean success",
valuetype = "boolean"
},
loadAsync = {
type = "method",
description = "Asynchronously copies the data from the given file into this object. This method is an asynchronous operation and will return immediately.\n\n–> MOAIDataBuffer self\n–> string filename: The path to the file that the data should be loaded from.\n–> MOAITaskQueue queue: The queue to perform the loading operation.\n[–> function callback: The function to be called when the asynchronous operation is complete. The MOAIDataBuffer is passed as the first parameter.]\n[–> number detectZip: One of MOAIDataBuffer.NO_INFLATE, MOAIDataBuffer.FORCE_INFLATE, MOAIDataBuffer.INFLATE_ON_EXT]\n[–> boolean inflateAsync: 'true' to inflate on task thread. 'false' to inflate on subscriber thread. Default value is 'true.']\n[–> number windowBits: The window bits used in the DEFLATE algorithm. Pass nil to use the default value.]\n<– MOAIDataIOTask task: A new MOAIDataIOTask which indicates the status of the task.",
args = "(MOAIDataBuffer self, string filename, MOAITaskQueue queue, [function callback, [number detectZip, [boolean inflateAsync, [number windowBits]]]])",
returns = "MOAIDataIOTask task",
valuetype = "MOAIDataIOTask"
},
save = {
type = "method",
description = "Saves the data in this object to the given file. This method is a synchronous operation and will block until the data is saved.\n\n–> MOAIDataBuffer self\n–> string filename: The path to the file that the data should be saved to.\n<– boolean success: Whether the data could be saved to the file.",
args = "(MOAIDataBuffer self, string filename)",
returns = "boolean success",
valuetype = "boolean"
},
saveAsync = {
type = "method",
description = "Asynchronously saves the data in this object to the given file. This method is an asynchronous operation and will return immediately.\n\n–> MOAIDataBuffer self\n–> string filename: The path to the file that the data should be saved to.\n–> MOAITaskQueue queue: The queue to perform the saving operation.\n[–> function callback: The function to be called when the asynchronous operation is complete. The MOAIDataBuffer is passed as the first parameter.]\n<– MOAIDataIOTask task: A new MOAIDataIOTask which indicates the status of the task.",
args = "(MOAIDataBuffer self, string filename, MOAITaskQueue queue, [function callback])",
returns = "MOAIDataIOTask task",
valuetype = "MOAIDataIOTask"
},
setString = {
type = "method",
description = "Replaces the contents of this object with the string specified.\n\n–> MOAIDataBuffer self\n–> string data: The string data to replace the contents of this object with.\n<– nil",
args = "(MOAIDataBuffer self, string data)",
returns = "nil"
},
toCppHeader = {
type = "function",
description = "Convert data to CPP header file.\n\nOverload:\n–> string data: The string data to encode\n–> string name\n[–> number columns: Default value is 12]\n<– string output\n\nOverload:\n–> MOAIDataBuffer data: The data buffer to encode\n–> string name\n[–> number columns: Default value is 12]\n<– string output",
args = "((string data | MOAIDataBuffer data), string name, [number columns])",
returns = "string output",
valuetype = "string"
}
}
},
MOAIDataBufferStream = {
type = "class",
inherits = "MOAIStream",
description = "MOAIDataBufferStream locks an associated MOAIDataBuffer for reading and writing.",
childs = {
close = {
type = "method",
description = "Disassociates and unlocks the stream's MOAIDataBuffer.\n\n–> MOAIDataBufferStream self\n<– nil",
args = "MOAIDataBufferStream self",
returns = "nil"
},
open = {
type = "method",
description = "Associate the stream with a MOAIDataBuffer. Note that the MOAIDataBuffer will be locked with a mutex while it is open thus blocking any asynchronous operations.\n\n–> MOAIDataBufferStream self\n–> MOAIDataBuffer buffer\n<– boolean success",
args = "(MOAIDataBufferStream self, MOAIDataBuffer buffer)",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIDebugLines = {
type = "class",
inherits = "MOAILuaObject",
description = "Singleton for managing rendering of world space debug vectors.",
childs = {
PARTITION_CELLS = {
type = "value"
},
PARTITION_PADDED_CELLS = {
type = "value"
},
PROP_MODEL_BOUNDS = {
type = "value"
},
PROP_WORLD_BOUNDS = {
type = "value"
},
TEXT_BOX = {
type = "value"
},
TEXT_BOX_BASELINES = {
type = "value"
},
TEXT_BOX_LAYOUT = {
type = "value"
},
setStyle = {
type = "function",
description = "Sets the particulars of a given debug line style.\n\n–> number styleID: See MOAIDebugLines class documentation for a list of styles.\n[–> number size: Pen size (in pixels) for the style. Default value is 1.]\n[–> number r: Red component of line color. Default value is 1.]\n[–> number g: Green component of line color. Default value is 1.]\n[–> number b: Blue component of line color. Default value is 1.]\n[–> number a: Alpha component of line color. Default value is 1.]\n<– nil",
args = "(number styleID, [number size, [number r, [number g, [number b, [number a]]]]])",
returns = "nil"
},
showStyle = {
type = "function",
description = "Enables or disables drawing of a given debug line style.\n\n–> number styleID: See MOAIDebugLines class documentation for a list of styles.\n[–> boolean show: Default value is 'true']\n<– nil",
args = "(number styleID, [boolean show])",
returns = "nil"
}
}
},
MOAIDeck = {
type = "class",
inherits = "MOAILuaObject",
description = "Base class for decks.",
childs = {
setBoundsDeck = {
type = "method",
description = "Set or clear the bounds override deck.\n\n–> MOAIDeck self\n[–> MOAIBoundsDeck boundsDeck]\n<– nil",
args = "(MOAIDeck self, [MOAIBoundsDeck boundsDeck])",
returns = "nil"
},
setShader = {
type = "method",
description = "Set the shader to use if neither the deck item nor the prop specifies a shader.\n\n–> MOAIDeck self\n–> MOAIShader shader\n<– nil",
args = "(MOAIDeck self, MOAIShader shader)",
returns = "nil"
},
setTexture = {
type = "method",
description = "Set or load a texture for this deck.\n\n–> MOAIDeck self\n–> variant texture: A MOAITexture, MOAIMultiTexture, MOAIDataBuffer or a path to a texture file\n[–> number transform: Any bitwise combination of MOAITextureBase.QUANTIZE, MOAITextureBase.TRUECOLOR, MOAITextureBase.PREMULTIPLY_ALPHA]\n<– MOAIGfxState texture",
args = "(MOAIDeck self, variant texture, [number transform])",
returns = "MOAIGfxState texture",
valuetype = "MOAIGfxState"
}
}
},
MOAIDeckRemapper = {
type = "class",
inherits = "MOAINode",
description = "Remap deck indices. Most useful for controlling animated tiles in tilemaps. All indices are exposed as attributes that may be connected by setAttrLink or driven using MOAIAnim or MOAIAnimCurve.",
childs = {
reserve = {
type = "method",
description = "The total number of indices to remap. Index remaps will be initialized from 1 to N.\n\n–> MOAIDeckRemapper self\n[–> number size: Default value is 0.]\n<– nil",
args = "(MOAIDeckRemapper self, [number size])",
returns = "nil"
},
setBase = {
type = "method",
description = "Set the base offset for the range of indices to remap. Used when remapping only a portion of the indices in the original deck.\n\n–> MOAIDeckRemapper self\n[–> number base: Default value is 0.]\n<– nil",
args = "(MOAIDeckRemapper self, [number base])",
returns = "nil"
},
setRemap = {
type = "method",
description = "Remap a single index to a new value.\n\n–> MOAIDeckRemapper self\n–> number index: Index to remap.\n[–> number remap: New value for index. Default value is index (i.e. remove the remap).]\n<– nil",
args = "(MOAIDeckRemapper self, number index, [number remap])",
returns = "nil"
}
}
},
MOAIDialogAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for a simple native dialog implementation on Android devices. Exposed to Lua via MOAIDialog on all mobile platforms.",
childs = {
DIALOG_RESULT_CANCEL = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the cancel button."
},
DIALOG_RESULT_NEGATIVE = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the negative button."
},
DIALOG_RESULT_NEUTRAL = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the neutral button."
},
DIALOG_RESULT_POSITIVE = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the positive button."
},
showDialog = {
type = "function",
description = "Show a native dialog to the user.\n\n–> string title: The title of the dialog box. Can be nil.\n–> string message: The message to show the user. Can be nil.\n–> string positive: The text for the positive response dialog button. Can be nil.\n–> string neutral: The text for the neutral response dialog button. Can be nil.\n–> string negative: The text for the negative response dialog button. Can be nil.\n–> boolean cancelable: Specifies whether or not the dialog is cancelable\n[–> function callback: A function to callback when the dialog is dismissed. Default is nil.]\n<– nil",
args = "(string title, string message, string positive, string neutral, string negative, boolean cancelable, [function callback])",
returns = "nil"
}
}
},
MOAIDialogIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for a simple native dialog implementation on iOS devices. Exposed to Lua via MOAIDialog on all mobile platforms.",
childs = {
DIALOG_RESULT_CANCEL = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the cancel button."
},
DIALOG_RESULT_NEGATIVE = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the negative button."
},
DIALOG_RESULT_NEUTRAL = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the neutral button."
},
DIALOG_RESULT_POSITIVE = {
type = "value",
description = "Result code when the dialog is dismissed by pressing the positive button."
}
}
},
MOAIDraw = {
type = "class",
inherits = "MOAILuaObject",
description = "Singleton for performing immediate mode drawing operations. See MOAIScriptDeck.",
childs = {
drawBoxOutline = {
type = "function",
description = "Draw a box outline.\n\n–> number x0\n–> number y0\n–> number z0\n–> number x1\n–> number y1\n–> number z1\n<– nil",
args = "(number x0, number y0, number z0, number x1, number y1, number z1)",
returns = "nil"
},
drawCircle = {
type = "function",
description = "Draw a circle.\n\n–> number x\n–> number y\n–> number r\n–> number steps\n<– nil",
args = "(number x, number y, number r, number steps)",
returns = "nil"
},
drawEllipse = {
type = "function",
description = "Draw an ellipse.\n\n–> number x\n–> number y\n–> number xRad\n–> number yRad\n–> number steps\n<– nil",
args = "(number x, number y, number xRad, number yRad, number steps)",
returns = "nil"
},
drawLine = {
type = "function",
description = "Draw a line.\n\n–> ... vertices: List of vertices (x, y) or an array of vertices { x0, y0, x1, y1, ... , xn, yn }\n<– nil",
args = "... vertices",
returns = "nil"
},
drawPoints = {
type = "function",
description = "Draw a list of points.\n\n–> ... vertices: List of vertices (x, y) or an array of vertices { x0, y0, x1, y1, ... , xn, yn }\n<– nil",
args = "... vertices",
returns = "nil"
},
drawRay = {
type = "function",
description = "Draw a ray.\n\n–> number x\n–> number y\n–> number dx\n–> number dy\n<– nil",
args = "(number x, number y, number dx, number dy)",
returns = "nil"
},
drawRect = {
type = "function",
description = "Draw a rectangle.\n\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n<– nil",
args = "(number x0, number y0, number x1, number y1)",
returns = "nil"
},
drawText = {
type = "function",
description = "Draws a string.\n\n–> MOAIFont font\n–> number size: Font size\n–> string text\n–> number x: Left position\n–> number y: Top position\n–> number scale\n–> number shadowOffsetX\n–> number shadowOffsetY\n<– nil",
args = "(MOAIFont font, number size, string text, number x, number y, number scale, number shadowOffsetX, number shadowOffsetY)",
returns = "nil"
},
drawTexture = {
type = "function",
description = "Draw a filled rectangle.\n\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> MOAITexture texture\n<– nil",
args = "(number x0, number y0, number x1, number y1, MOAITexture texture)",
returns = "nil"
},
fillCircle = {
type = "function",
description = "Draw a filled circle.\n\n–> number x\n–> number y\n–> number r\n–> number steps\n<– nil",
args = "(number x, number y, number r, number steps)",
returns = "nil"
},
fillEllipse = {
type = "function",
description = "Draw a filled ellipse.\n\n–> number x\n–> number y\n–> number xRad\n–> number yRad\n–> number steps\n<– nil",
args = "(number x, number y, number xRad, number yRad, number steps)",
returns = "nil"
},
fillFan = {
type = "function",
description = "Draw a filled fan.\n\n–> ... vertices: List of vertices (x, y) or an array of vertices { x0, y0, x1, y1, ... , xn, yn }\n<– nil",
args = "... vertices",
returns = "nil"
},
fillRect = {
type = "function",
description = "Draw a filled rectangle.\n\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n<– nil",
args = "(number x0, number y0, number x1, number y1)",
returns = "nil"
}
}
},
MOAIEaseDriver = {
type = "class",
inherits = "MOAITimer",
description = "Action that applies simple ease curves to node attributes.",
childs = {
reserveLinks = {
type = "method",
description = "Reserve links.\n\n–> MOAIEaseDriver self\n–> number nLinks\n<– nil",
args = "(MOAIEaseDriver self, number nLinks)",
returns = "nil"
},
setLink = {
type = "method",
description = "Set the ease for a target node attribute.\n\nOverload:\n–> MOAIEaseDriver self\n–> number idx: Index of the link;\n–> MOAINode target: Target node.\n–> number attrID: Index of the attribute to be driven.\n[–> number value: Value for attribute at the end of the ease. Default is 0.]\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– nil\n\nOverload:\n–> MOAIEaseDriver self\n–> number idx: Index of the link;\n–> MOAINode target: Target node.\n–> number attrID: Index of the attribute to be driven.\n–> MOAINode source: Node that you are linking to target.\n–> number sourceAttrID: Index of the attribute being linked.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– nil"
}
}
},
MOAIEaseType = {
type = "class",
inherits = "MOAILuaObject",
description = "Namespace to hold ease modes. Moai ease in/out has opposite meaning of Flash ease in/out.",
childs = {
EASE_IN = {
type = "value",
description = "Quartic ease in - Fast start then slow when approaching value; ease into position."
},
EASE_OUT = {
type = "value",
description = "Quartic ease out - Slow start then fast when approaching value; ease out of position."
},
FLAT = {
type = "value",
description = "Stepped change - Maintain original value until end of ease."
},
LINEAR = {
type = "value",
description = "Linear interpolation."
},
SHARP_EASE_IN = {
type = "value",
description = "Octic ease in."
},
SHARP_EASE_OUT = {
type = "value",
description = "Octic ease out."
},
SHARP_SMOOTH = {
type = "value",
description = "Octic smooth."
},
SMOOTH = {
type = "value",
description = "Quartic ease out then ease in."
},
SOFT_EASE_IN = {
type = "value",
description = "Quadratic ease in."
},
SOFT_EASE_OUT = {
type = "value",
description = "Quadratic ease out."
},
SOFT_SMOOTH = {
type = "value",
description = "Quadratic smooth."
}
}
},
MOAIEnvironment = {
type = "class",
inherits = "MOAILuaObject",
description = "Table of key/value pairs containing information about the current environment. Also contains the generateGUID (), which will move to MOAIUnique in a future release.\nIf a given key is not supported in the current environment it will not exist (it's value will be nil).\nThe keys are:\n- appDisplayName\n- appID\n- appVersion\n- cacheDirectory\n- carrierISOCountryCode\n- carrierMobileCountryCode\n- carrierMobileNetworkCode\n- carrierName\n- connectionType\n- countryCode\n- cpuabi\n- devBrand\n- devName\n- devManufacturer\n- devModel\n- devPlatform\n- devProduct\n- documentDirectory\n- iosRetinaDisplay\n- languageCode\n- numProcessors\n- osBrand\n- osVersion\n- resourceDirectory\n- screenDpi\n- verticalResolution\n- horizontalResolution\n- udid\n- openUdid",
childs = {
CONNECTION_TYPE_NONE = {
type = "value",
description = "Signifies that there is no active connection"
},
CONNECTION_TYPE_WIFI = {
type = "value",
description = "Signifies that the current connection is via WiFi"
},
CONNECTION_TYPE_WWAN = {
type = "value",
description = "Signifies that the current connection is via WWAN"
},
OS_BRAND_ANDROID = {
type = "value",
description = "Signifies that Moai is currently running on Android"
},
OS_BRAND_IOS = {
type = "value",
description = "Signifies that Moai is currently running on iOS"
},
OS_BRAND_LINUX = {
type = "value",
description = "Signifies that Moai is currently running on Linux"
},
OS_BRAND_OSX = {
type = "value",
description = "Signifies that Moai is currently running on OSX"
},
OS_BRAND_UNAVAILABLE = {
type = "value",
description = "Signifies that the operating system cannot be determined"
},
OS_BRAND_WINDOWS = {
type = "value",
description = "Signifies that Moai is currently running on Windows"
},
generateGUID = {
type = "function",
description = "Generates a globally unique identifier. This method will be moved to MOAIUnique in a future release.\n\n<– string GUID",
args = "()",
returns = "string GUID",
valuetype = "string"
},
getMACAddress = {
type = "function",
description = "Finds and returns the primary MAC Address\n\n<– string MAC",
args = "()",
returns = "string MAC",
valuetype = "string"
},
setValue = {
type = "function",
description = "Sets an environment value and also triggers the listener callback (if any).\n\n–> string key\n[–> variant value: Default value is nil.]\n<– nil",
args = "(string key, [variant value])",
returns = "nil"
}
}
},
MOAIEventSource = {
type = "class",
inherits = "MOAILuaObject",
description = "Base class for all Lua-bound Moai objects that emit events and have an event table.",
childs = {}
},
MOAIFacebookAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Facebook integration on Android devices. Facebook provides social integration for sharing on www.facebook.com. Exposed to Lua via MOAIFacebook on all mobile platforms.",
childs = {
DIALOG_DID_COMPLETE = {
type = "value",
description = "Event code for a successfully completed Facebook dialog."
},
DIALOG_DID_NOT_COMPLETE = {
type = "value",
description = "Event code for a failed (or canceled) Facebook dialog."
},
REQUEST_RESPONSE = {
type = "value",
description = "Event code for graph request responses."
},
REQUEST_RESPONSE_FAILED = {
type = "value",
description = "Event code for failed graph request responses."
},
SESSION_DID_LOGIN = {
type = "value",
description = "Event code for a successfully completed Facebook login."
},
SESSION_DID_NOT_LOGIN = {
type = "value",
description = "Event code for a failed (or canceled) Facebook login."
},
extendToken = {
type = "function",
description = "Extend the token if needed\n\n<– nil",
args = "()",
returns = "nil"
},
getExpirationDate = {
type = "function",
description = "Retrieve the Facebook login token expiration date.\n\n<– string expirationDate: token expiration date",
args = "()",
returns = "string expirationDate",
valuetype = "string"
},
getToken = {
type = "function",
description = "Retrieve the Facebook login token.\n\n<– string token",
args = "()",
returns = "string token",
valuetype = "string"
},
graphRequest = {
type = "function",
description = "Make a request on Facebook's Graph API\n\n–> string path\n[–> table parameters]\n<– nil",
args = "(string path, [table parameters])",
returns = "nil"
},
init = {
type = "function",
description = "Initialize Facebook.\n\n–> string appId: Available in Facebook developer settings.\n<– nil",
args = "string appId",
returns = "nil"
},
login = {
type = "function",
description = "Prompt the user to login to Facebook.\n\n[–> table permissions: Optional set of required permissions. See Facebook documentation for a full list. Default is nil.]\n<– nil",
args = "[table permissions]",
returns = "nil"
},
logout = {
type = "function",
description = "Log the user out of Facebook.\n\n<– nil",
args = "()",
returns = "nil"
},
postToFeed = {
type = "function",
description = "Post a message to the logged in users' news feed.\n\n–> string link: The URL that the post links to. See Facebook documentation.\n–> string picture: The URL of an image to include in the post. See Facebook documentation.\n–> string name: The name of the link. See Facebook documentation.\n–> string caption: The caption of the link. See Facebook documentation.\n–> string description: The description of the link. See Facebook documentation.\n–> string message: The message for the post. See Facebook documentation.\n<– nil",
args = "(string link, string picture, string name, string caption, string description, string message)",
returns = "nil"
},
sendRequest = {
type = "function",
description = "Send an app request to the logged in users' friends.\n\n[–> string message: The message for the request. See Facebook documentation. Default is nil.]\n<– nil",
args = "[string message]",
returns = "nil"
},
sessionValid = {
type = "function",
description = "Determine whether or not the current Facebook session is valid.\n\n<– boolean valid",
args = "()",
returns = "boolean valid",
valuetype = "boolean"
},
setExpirationDate = {
type = "function",
description = "Set the Facebook login token expiration date.\n\n–> string expirationDate: The login token expiration date. See Facebook documentation.\n<– nil",
args = "string expirationDate",
returns = "nil"
},
setToken = {
type = "function",
description = "Set the Facebook login token.\n\n–> string token: The login token. See Facebook documentation.\n<– nil",
args = "string token",
returns = "nil"
}
}
},
MOAIFacebookIOS = {
type = "class",
inherits = "MOAIGlobalEventSource",
description = "Wrapper for Facebook integration on iOS devices. Facebook provides social integration for sharing on www.facebook.com. Exposed to Lua via MOAIFacebook on all mobile platforms.",
childs = {
DIALOG_DID_COMPLETE = {
type = "value",
description = "Event code for a successfully completed Facebook dialog."
},
DIALOG_DID_NOT_COMPLETE = {
type = "value",
description = "Event code for a failed (or canceled) Facebook dialog."
},
REQUEST_RESPONSE = {
type = "value",
description = "Event code for graph request responses."
},
REQUEST_RESPONSE_FAILED = {
type = "value",
description = "Event code for failed graph request responses."
},
SESSION_DID_LOGIN = {
type = "value",
description = "Event code for a successfully completed Facebook login."
},
SESSION_DID_NOT_LOGIN = {
type = "value",
description = "Event code for a failed (or canceled) Facebook login."
}
}
},
MOAIFileStream = {
type = "class",
inherits = "MOAIStream",
description = "MOAIFileStream opens a system file handle for reading or writing.",
childs = {
READ = {
type = "value"
},
READ_WRITE = {
type = "value"
},
READ_WRITE_AFFIRM = {
type = "value"
},
READ_WRITE_NEW = {
type = "value"
},
WRITE = {
type = "value"
},
close = {
type = "method",
description = "Close and release the associated file handle.\n\n–> MOAIFileStream self\n<– nil",
args = "MOAIFileStream self",
returns = "nil"
},
open = {
type = "method",
description = "Open or create a file stream given a valid path.\n\n–> MOAIFileStream self\n–> string fileName\n[–> number mode: One of MOAIFileStream.APPEND, MOAIFileStream.READ, MOAIFileStream.READ_WRITE, MOAIFileStream.READ_WRITE_AFFIRM, MOAIFileStream.READ_WRITE_NEW, MOAIFileStream.WRITE. Default value is MOAIFileStream.READ.]\n<– boolean success",
args = "(MOAIFileStream self, string fileName, [number mode])",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIFileSystem = {
type = "class",
inherits = "MOAILuaObject",
description = "Functions for manipulating the file system.",
childs = {
affirmPath = {
type = "function",
description = "Creates a folder at 'path' if none exists.\n\n–> string path\n<– nil",
args = "string path",
returns = "nil"
},
checkFileExists = {
type = "function",
description = "Check for the existence of a file.\n\n–> string filename\n<– boolean exists",
args = "string filename",
returns = "boolean exists",
valuetype = "boolean"
},
checkPathExists = {
type = "function",
description = "Check for the existence of a path.\n\n–> string path\n<– boolean exists",
args = "string path",
returns = "boolean exists",
valuetype = "boolean"
},
copy = {
type = "function",
description = "Copy a file or directory to a new location.\n\n–> string srcPath\n–> string destPath\n<– boolean result",
args = "(string srcPath, string destPath)",
returns = "boolean result",
valuetype = "boolean"
},
deleteDirectory = {
type = "function",
description = "Deletes a directory and all of its contents.\n\n–> string path\n[–> boolean recursive: If true, the directory and all contents beneath it will be purged. Otherwise, the directory will only be removed if empty.]\n<– boolean success",
args = "(string path, [boolean recursive])",
returns = "boolean success",
valuetype = "boolean"
},
deleteFile = {
type = "function",
description = "Deletes a file.\n\n–> string filename\n<– boolean success",
args = "string filename",
returns = "boolean success",
valuetype = "boolean"
},
getAbsoluteDirectoryPath = {
type = "function",
description = "Returns the absolute path given a relative path.\n\n–> string path\n<– string absolute",
args = "string path",
returns = "string absolute",
valuetype = "string"
},
getAbsoluteFilePath = {
type = "function",
description = "Returns the absolute path to a file. Result includes the file name.\n\n–> string filename\n<– string absolute",
args = "string filename",
returns = "string absolute",
valuetype = "string"
},
getRelativePath = {
type = "function",
description = "Given an absolute path returns the relative path in relation to the current working directory.\n\n–> string path\n<– string path: -",
args = "string path",
returns = "string path",
valuetype = "string"
},
getWorkingDirectory = {
type = "function",
description = "Returns the path to current working directory.\n\n<– string path",
args = "()",
returns = "string path",
valuetype = "string"
},
listDirectories = {
type = "function",
description = "Lists the sub-directories contained in a directory.\n\n[–> string path: Path to search. Default is current directory.]\n<– table diresctories: A table of directory names (or nil if the path is invalid)",
args = "[string path]",
returns = "table diresctories",
valuetype = "table"
},
listFiles = {
type = "function",
description = "Lists the files contained in a directory\n\n[–> string path: Path to search. Default is current directory.]\n<– table files: A table of filenames (or nil if the path is invalid)",
args = "[string path]",
returns = "table files",
valuetype = "table"
},
mountVirtualDirectory = {
type = "function",
description = "Mount an archive as a virtual filesystem directory.\n\n–> string path: Virtual path.\n[–> string archive: Name of archive file to mount. Default value is nil.]\n<– boolean success",
args = "(string path, [string archive])",
returns = "boolean success",
valuetype = "boolean"
},
rename = {
type = "function",
description = "Renames a file or folder.\n\n–> string oldPath\n–> string newPath\n<– boolean success",
args = "(string oldPath, string newPath)",
returns = "boolean success",
valuetype = "boolean"
},
setWorkingDirectory = {
type = "function",
description = "Sets the current working directory.\n\n–> string path\n<– boolean success",
args = "string path",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIFmodEventInstance = {
type = "class",
inherits = "MOAITransform",
description = "An instance of an FMOD Event Not to be confused with an Event, MOAIFmodEvent.",
childs = {
getBeatFraction = {
type = "method",
description = "Returns the beat fraction of this Event Instance (useful for music)\n\n–> MOAIFmodEventInstance self\n<– number beatFraction: Beat Fraction of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number beatFraction",
valuetype = "number"
},
getDominantFrequency = {
type = "method",
description = "Returns the fundamental frequency of this Event Instance.\n\n–> MOAIFmodEventInstance self\n<– number frequency: Dominant frequency of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number frequency",
valuetype = "number"
},
getMeasureFraction = {
type = "method",
description = "Returns the measure fraction of this Event Instance (useful for music)\n\n–> MOAIFmodEventInstance self\n<– number measureFraction: Measure Fraction of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number measureFraction",
valuetype = "number"
},
getName = {
type = "method",
description = "Get the name of the Event\n\n–> MOAIFmodEventInstance self\n<– string name: Name of the event",
args = "MOAIFmodEventInstance self",
returns = "string name",
valuetype = "string"
},
getNumChannels = {
type = "method",
description = "Get the number of Channels in this Event's Channel Group\n\n–> MOAIFmodEventInstance self\n<– number channels: Number of channels in Event Instance's Channel Group",
args = "MOAIFmodEventInstance self",
returns = "number channels",
valuetype = "number"
},
getParameter = {
type = "method",
description = "Gets the value (a number) of an Event parameter\n\n–> MOAIFmodEventInstance self\n–> string parameterName: The name of the Event Parameter\n<– number paramValue: The value of the Event Parameter",
args = "(MOAIFmodEventInstance self, string parameterName)",
returns = "number paramValue",
valuetype = "number"
},
getPitch = {
type = "method",
description = "Gets the pitch of the Event Instance.\n\n–> MOAIFmodEventInstance self\n<– number pitch: pitch of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number pitch",
valuetype = "number"
},
getTempo = {
type = "method",
description = "Returns the tempo of this Event Instance (useful for music)\n\n–> MOAIFmodEventInstance self\n<– number tempo: Tempo of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number tempo",
valuetype = "number"
},
getTime = {
type = "method",
description = "Returns time within the Event, or if useSubsoundTime, will return the time within the *the first subsound only*\n\n–> MOAIFmodEventInstance self\n[–> boolean useSubsoundTime: If true, will return the time within the first subsound only (Default: false)]\n<– number time: Time within the Event",
args = "(MOAIFmodEventInstance self, [boolean useSubsoundTime])",
returns = "number time",
valuetype = "number"
},
getVolume = {
type = "method",
description = "Gets the volume of the Event Instance.\n\n–> MOAIFmodEventInstance self\n<– number volume: volume of this Event Instance",
args = "MOAIFmodEventInstance self",
returns = "number volume",
valuetype = "number"
},
isValid = {
type = "method",
description = "Checks to see if the instance is valid (i.e., currently playing)\n\n–> MOAIFmodEventInstance self\n<– boolean valid: True if the instance is currently playing, false otherwise",
args = "MOAIFmodEventInstance self",
returns = "boolean valid",
valuetype = "boolean"
},
keyOff = {
type = "method",
description = "Sets the Event Instance to key off based on the passed in Event Parameter\n\n–> MOAIFmodEventInstance self\n–> string parameterName: The name of the Event Parameter\n<– nil",
args = "(MOAIFmodEventInstance self, string parameterName)",
returns = "nil"
},
mute = {
type = "method",
description = "Mutes the Event Instance currently playing.\n\n–> MOAIFmodEventInstance self\n[–> boolean setting: Whether to mute or unmute. Defaults to true (mute).]\n<– nil",
args = "(MOAIFmodEventInstance self, [boolean setting])",
returns = "nil"
},
pause = {
type = "method",
description = "Pauses the Event Instance currently playing.\n\n–> MOAIFmodEventInstance self\n[–> boolean setting: Whether to pause or unpause. Defaults to true (pause).]\n<– nil",
args = "(MOAIFmodEventInstance self, [boolean setting])",
returns = "nil"
},
setParameter = {
type = "method",
description = "Sets the value (a number) of an Event parameter\n\n–> MOAIFmodEventInstance self\n–> string parameterName: The name of the Event Parameter\n–> number paramValue: New value of the Event Parameter\n<– nil",
args = "(MOAIFmodEventInstance self, string parameterName, number paramValue)",
returns = "nil"
},
setPitch = {
type = "method",
description = "Sets the pitch of the Event Instance.\n\n–> MOAIFmodEventInstance self\n–> number pitch: A pitch level, from 0.0 to 10.0 inclusive. 0.5 = half pitch, 2.0 = double pitch. Default = 1.0\n<– nil",
args = "(MOAIFmodEventInstance self, number pitch)",
returns = "nil"
},
setVolume = {
type = "method",
description = "Sets the volume of the Event Instance.\n\n–> MOAIFmodEventInstance self\n–> number volume: Volume is a number between 0 and 1 (where 1 is at full volume).\n<– nil",
args = "(MOAIFmodEventInstance self, number volume)",
returns = "nil"
},
stop = {
type = "method",
description = "Stops the Event Instance from playing.\n\n–> MOAIFmodEventInstance self\n<– nil",
args = "MOAIFmodEventInstance self",
returns = "nil"
},
unloadOnSilence = {
type = "method",
description = "For streaming sounds -- unloads the Event from memory on silence. (A good guideline to use is: for sounds that don't repeat often)\n\n–> MOAIFmodEventInstance self\n[–> boolean setting: Whether to unload on silence or not (Default: true)]\n<– nil",
args = "(MOAIFmodEventInstance self, [boolean setting])",
returns = "nil"
}
}
},
MOAIFmodEventMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "Event Manager singleton that provides an interface to all implemented FMOD Designer features.",
childs = {
getEventDuration = {
type = "function",
description = "Returns the duration of an Event. Although multiple sounds can potentially be played from 1 Event, to support determinism, a consistent duration will be returned for a given Event.\n\n–> string eventName: The name of the Event\n[–> string lineName: Pass this is if you want the duration of a voice line]\n<– number duration: Duration of the Event, nil if Event is invalid",
args = "(string eventName, [string lineName])",
returns = "number duration",
valuetype = "number"
},
getMemoryStats = {
type = "function",
description = "Get memory usage.\n\n[–> boolean blocking: Default value is 'false.']\n<– number currentAlloc\n<– number maxAlloc",
args = "[boolean blocking]",
returns = "(number currentAlloc, number maxAlloc)",
valuetype = "number"
},
getMicrophone = {
type = "function",
description = "Returns the game microphone.\n\n<– MOAIFmodMicrophone mic: The game microphone",
args = "()",
returns = "MOAIFmodMicrophone mic",
valuetype = "MOAIFmodMicrophone"
},
getSoundCategoryVolume = {
type = "function",
description = "Gets the volume for a sound category\n\n–> string categoryName: Name of the category whose volume you wanna know\n<– number categoryVolume: The volume of the category",
args = "string categoryName",
returns = "number categoryVolume",
valuetype = "number"
},
init = {
type = "function",
description = "Initializes the sound system.\n\n<– boolean enabled",
args = "()",
returns = "boolean enabled",
valuetype = "boolean"
},
isEnabled = {
type = "function",
description = "Returns true if the Event Manager is enabled (active).\n\n<– boolean enabled: True if the Event Manager is active, false otherwise",
args = "()",
returns = "boolean enabled",
valuetype = "boolean"
},
isSoundCategoryMuted = {
type = "function",
description = "Checks to see whether a sound category is muted\n\n–> string categoryName: Name of the category whose volume you wanna know\n<– boolean isMuted: Returns whether the sound category is muted",
args = "string categoryName",
returns = "boolean isMuted",
valuetype = "boolean"
},
isSoundCategoryPaused = {
type = "function",
description = "Checks to see whether a sound category is muted\n\n–> string categoryName: Name of the category whose volume you wanna know\n<– boolean isMuted: Returns whether the sound category is muted",
args = "string categoryName",
returns = "boolean isMuted",
valuetype = "boolean"
},
loadGroup = {
type = "function",
description = "Loads the wave data and instance data associated with a particular group. Groups are reference counted internally, with each call to LoadGroup incrementing the ref count.\n\n–> string groupPath: Should be of the form ProjectName/GroupName\n–> boolean persistent: Passing true means that this group is expected to be around for the entire duration of the app\n–> boolean blockOnLoad: Passing true means that the main thread will block while loading wav data for this Group.\n<– boolean loaded: True if the Group successfully loaded after this call, false otherwise",
args = "(string groupPath, boolean persistent, boolean blockOnLoad)",
returns = "boolean loaded",
valuetype = "boolean"
},
loadProject = {
type = "function",
description = "Loads a project from disk, but does not load any wav or instance data. Projects must be loaded before sounds can be played from them. For special voice projects, use loadVoiceProject()\n\n–> string projectName: The name of the .fev file (path should be relative from project root)\n<– boolean loaded: True if the project successfully loaded, false otherwise",
args = "string projectName",
returns = "boolean loaded",
valuetype = "boolean"
},
loadVoiceProject = {
type = "function",
description = "Calls LoadProject and does all attendant special voice load stuff, as well. For regular projects, use loadProject()\n\n–> string projectName: The name of the .fsb file (path should be relative from project root)\n<– boolean loaded: True if the voice project successfully loaded, false otherwise",
args = "string projectName",
returns = "boolean loaded",
valuetype = "boolean"
},
muteAllEvents = {
type = "function",
description = "Stops all events/sounds from playing.\n\n–> boolean muteSetting: Whether to mute (true) or unmute (false)\n<– nil",
args = "boolean muteSetting",
returns = "nil"
},
muteSoundCategory = {
type = "function",
description = "Mute a sound category\n\n–> string categoryName: Name of the category whose volume you wanna modify\n–> boolean muteSetting: Whether to mute the category or not (Default: true)\n<– nil",
args = "(string categoryName, boolean muteSetting)",
returns = "nil"
},
pauseSoundCategory = {
type = "function",
description = "Mute a sound category\n\n–> string categoryName: Name of the category whose volume you wanna modify\n–> boolean pauseSetting: Whether to mute the category or not (Default: true)\n<– nil",
args = "(string categoryName, boolean pauseSetting)",
returns = "nil"
},
playEvent2D = {
type = "function",
description = "Plays an FMOD Event in 2D. Calling this function on 3D Events is undefined.\n\n–> string eventName: Event to play\n[–> boolean loopSound: Will force the Event to loop even if it does not in the data.]\n<– MOAIFmodEventInstance eventInst: The Event instance",
args = "(string eventName, [boolean loopSound])",
returns = "MOAIFmodEventInstance eventInst",
valuetype = "MOAIFmodEventInstance"
},
playEvent3D = {
type = "function",
description = "Plays an FMOD Event 3D. Calling this function on 2D Events is harmless, but not advised.\n\n–> string eventName: Event to play\n[–> number x: x position of this sound]\n[–> number y: y position of this sound]\n[–> number z: z position of this sound]\n[–> boolean loopSound: Will force the Event to loop even if it does not in the data.]\n<– MOAIFmodEventInstance eventInst: The Event instance",
args = "(string eventName, [number x, [number y, [number z, [boolean loopSound]]]])",
returns = "MOAIFmodEventInstance eventInst",
valuetype = "MOAIFmodEventInstance"
},
playVoiceLine = {
type = "function",
description = "Plays a voice line that exists in a loaded voice project. Will play it 2D or 3D based on Event settings. Uses a unique identifier for the line that is not the name of the Event -- although the event serves as a template for how the line will play.\n\n–> string linename: Unique identifier for a voice line\n–> string eventName: The Event template to use for playing this line\n[–> number x: x position of this sound]\n[–> number y: y position of this sound]\n[–> number z: z position of this sound]\n<– MOAIFmodEventInstance eventInst: The Event instance",
args = "(string linename, string eventName, [number x, [number y, [number z]]])",
returns = "MOAIFmodEventInstance eventInst",
valuetype = "MOAIFmodEventInstance"
},
preloadVoiceLine = {
type = "function",
description = "Preload a high demand voice line\n\n–> string eventName: The Event template to use for this line\n–> string lineName: The unique ID of the line to preload\n<– nil",
args = "(string eventName, string lineName)",
returns = "nil"
},
setDefaultReverb = {
type = "function",
description = "Set the default regional Reverb\n\n–> string reverbName: Name of the Reverb (defined in Designer)\n<– nil",
args = "string reverbName",
returns = "nil"
},
setDistantOcclusion = {
type = "function",
description = "Sets a lowpass filter on distant sounds -- a filter added to everything greater than a certain distance (minRange to maxRange) from the microphone to make it sound muffled/far away.\n\n–> number minRange: Minimum distance from mic\n–> number maxRange: Maximum distance from mic\n–> number maxOcclusion: Maximum occlusion value\n<– nil",
args = "(number minRange, number maxRange, number maxOcclusion)",
returns = "nil"
},
setNear2DBlend = {
type = "function",
description = "Blend sounds near the microphone to 2D sounds. When 3D Events are playing near the microphone, their positioning becomes distracting rather than helpful/interesting, so this is a way to blend them together as if they were all taking place just at the mic.\n\n–> number minRange: Minimum distance from mic\n–> number maxRange: Maximum distance from mic\n–> number maxLevel: Maximum pan level\n<– nil",
args = "(number minRange, number maxRange, number maxLevel)",
returns = "nil"
},
setSoundCategoryVolume = {
type = "function",
description = "Sets the volume for a sound category\n\n–> string categoryName: Name of the category whose volume you wanna modify\n–> number newVolume: New volume to set for the category\n<– nil",
args = "(string categoryName, number newVolume)",
returns = "nil"
},
stopAllEvents = {
type = "function",
description = "Stops all events/sounds from playing.\n\n<– nil",
args = "()",
returns = "nil"
},
unloadAllVoiceProjects = {
type = "function",
description = "Calls UnloadProject and does all attendant special voice unload stuff, as well. For regular projects, use unloadProject()\n\n<– boolean unloaded: True if voice projects are no longer loaded after this call, false otherwise.",
args = "()",
returns = "boolean unloaded",
valuetype = "boolean"
},
unloadEvent = {
type = "function",
description = "Unloads the data associated with an Event. All instances of this Event will be stopped when this call is made. Returns true if the Event is no longer loaded after this call.\n\n–> string eventName: The name of the Event\n[–> boolean blockOnUnload: Passing true means that the main thread will block while unloading]\n<– boolean eventUnloaded: True if the Event is no longer loaded after this call.",
args = "(string eventName, [boolean blockOnUnload])",
returns = "boolean eventUnloaded",
valuetype = "boolean"
},
unloadGroup = {
type = "function",
description = "Unloads the wave data and instance data associated with a particular group. Groups might not be unloaded immediately either because their reference count is not zero, or because the sound system is not ready to release the group.\n\n–> string groupPath: Should be of the form ProjectName/GroupName\n–> boolean unloadImmediately: If true is passed in, it'll try to unload now, but won't block. Passing false will allow it to wait before trying to unload\n<– boolean unloaded: True if the Group is no longer loaded after this call, false otherwise",
args = "(string groupPath, boolean unloadImmediately)",
returns = "boolean unloaded",
valuetype = "boolean"
},
unloadPendingUnloads = {
type = "function",
description = "Unloads all the pending unload groups. Use between act changes in the game.\n\n[–> boolean blockOnUnload: Passing true means that the main thread will block while unloading]\n<– nil",
args = "[boolean blockOnUnload]",
returns = "nil"
},
unloadProject = {
type = "function",
description = "Unloads all data associated with a particular project. Completely flushes all memory associated with the project. For special voice projects, use unloadAllVoiceProjects()\n\n–> string projectName: The name of the .fev file (path should be relative from project root)\n<– boolean unloaded: True if the project is no longer loaded after this call, false otherwise.",
args = "string projectName",
returns = "boolean unloaded",
valuetype = "boolean"
}
}
},
MOAIFmodEx = {
type = "class",
inherits = "MOAILuaObject",
description = "FMOD singleton.",
childs = {
getMemoryStats = {
type = "function",
description = "Get memory usage.\n\n[–> boolean blocking: Default value is 'false.']\n<– number currentAlloc\n<– number maxAlloc",
args = "[boolean blocking]",
returns = "(number currentAlloc, number maxAlloc)",
valuetype = "number"
},
init = {
type = "function",
description = "Initializes the sound system.\n\n<– nil",
args = "()",
returns = "nil"
}
}
},
MOAIFmodExChannel = {
type = "class",
inherits = "MOAINode",
description = "FMOD singleton.",
childs = {
getVolume = {
type = "method",
description = "Returns the current volume of the channel.\n\n–> MOAIFmodExChannel self\n<– number volume: the volume currently set in this channel.",
args = "MOAIFmodExChannel self",
returns = "number volume",
valuetype = "number"
},
isPlaying = {
type = "method",
description = "Returns true if channel is playing.\n\n–> MOAIFmodExChannel self\n<– boolean",
args = "MOAIFmodExChannel self",
returns = "boolean",
valuetype = "boolean"
},
moveVolume = {
type = "method",
description = "Creates a new MOAIAction that will move the volume from it's current value to the value specified.\n\n–> MOAIFmodExChannel self\n–> number target: The target volume.\n–> number delay: The delay until the action starts.\n–> number mode: The interpolation mode for the action.\n<– MOAIAction action: The new action. It is automatically started by this function.",
args = "(MOAIFmodExChannel self, number target, number delay, number mode)",
returns = "MOAIAction action",
valuetype = "MOAIAction"
},
play = {
type = "method",
description = "Plays the specified sound, looping it if desired.\n\n–> MOAIFmodExChannel self\n–> MOAIFmodExSound sound: The sound to play.\n–> number loopCount: Number of loops.\n<– nil",
args = "(MOAIFmodExChannel self, MOAIFmodExSound sound, number loopCount)",
returns = "nil"
},
seekVolume = {
type = "method",
description = "Creates a new MOAIAction that will move the volume from it's current value to the value specified.\n\n–> MOAIFmodExChannel self\n–> number target: The target volume.\n–> number delay: The delay until the action starts.\n–> number mode: The interpolation mode for the action.\n<– MOAIAction action: The new action. It is automatically started by this function.",
args = "(MOAIFmodExChannel self, number target, number delay, number mode)",
returns = "MOAIAction action",
valuetype = "MOAIAction"
},
setLooping = {
type = "method",
description = "Immediately sets looping for this channel.\n\n–> MOAIFmodExChannel self\n–> boolean looping: True if channel should loop.\n<– nil",
args = "(MOAIFmodExChannel self, boolean looping)",
returns = "nil"
},
setPaused = {
type = "method",
description = "Sets whether this channel is paused and hence does not play any sounds.\n\n–> MOAIFmodExChannel self\n–> boolean paused: Whether this channel is paused.\n<– nil",
args = "(MOAIFmodExChannel self, boolean paused)",
returns = "nil"
},
setVolume = {
type = "method",
description = "Immediately sets the volume of this channel.\n\n–> MOAIFmodExChannel self\n–> number volume: The volume of this channel.\n<– nil",
args = "(MOAIFmodExChannel self, number volume)",
returns = "nil"
},
stop = {
type = "method",
description = "Stops playing the sound on this channel.\n\n–> MOAIFmodExChannel self\n<– nil",
args = "MOAIFmodExChannel self",
returns = "nil"
}
}
},
MOAIFmodExSound = {
type = "class",
inherits = "MOAILuaObject",
description = "FMOD singleton.",
childs = {
load = {
type = "method",
description = "Loads the specified sound from file, or from a MOAIDataBuffer.\n\nOverload:\n–> MOAIFmodExSound self\n–> string filename: The path to the sound to load from file.\n–> boolean streaming: Whether the sound should be streamed from the data source, rather than preloaded.\n–> boolean async: Whether the sound file should be loaded asynchronously.\n<– nil\n\nOverload:\n–> MOAIFmodExSound self\n–> MOAIDataBuffer data: The MOAIDataBuffer that is storing sound data. You must either provide a string or MOAIDataBuffer, but not both.\n–> boolean streaming: Whether the sound should be streamed from the data source, rather than preloaded.\n<– nil",
args = "(MOAIFmodExSound self, ((string filename, boolean streaming, boolean async) | (MOAIDataBuffer data, boolean streaming)))",
returns = "nil"
},
loadBGM = {
type = "method",
description = "Loads the specified BGM sound from file, or from a MOAIDataBuffer.\n\nOverload:\n–> MOAIFmodExSound self\n–> string filename: The path to the sound to load from file.\n<– nil\n\nOverload:\n–> MOAIFmodExSound self\n–> MOAIDataBuffer data: The MOAIDataBuffer that is storing sound data.\n<– nil",
args = "(MOAIFmodExSound self, (string filename | MOAIDataBuffer data))",
returns = "nil"
},
loadSFX = {
type = "method",
description = "Loads the specified SFX sound from file, or from a MOAIDataBuffer.\n\nOverload:\n–> MOAIFmodExSound self\n–> string filename: The path to the sound to load from file.\n<– nil\n\nOverload:\n–> MOAIFmodExSound self\n–> MOAIDataBuffer data: The MOAIDataBuffer that is storing sound data.\n<– nil",
args = "(MOAIFmodExSound self, (string filename | MOAIDataBuffer data))",
returns = "nil"
},
release = {
type = "method",
description = "Releases the sound data from memory.\n\n–> MOAIFmodExSound self\n<– nil",
args = "MOAIFmodExSound self",
returns = "nil"
}
}
},
MOAIFmodMicrophone = {
type = "class",
inherits = "MOAITransform",
description = "The in-game Microphone, with respect to which all the sounds are heard in the game. The Event Manager (MOAIFmodEventManager) must be initialized before the Microphone can be accessed. Should only be grabbed from MOAIFmodEventMgr",
childs = {}
},
MOAIFont = {
type = "class",
inherits = "MOAILuaObject",
description = "MOAIFont is the top level object for managing sets of glyphs associated with a single font face. An instance of MOAIFont may contain glyph sets for multiple sizes of the font. Alternatively, a separate instance of MOAIFont may be used for each font size. Using a single font object for each size of a font face can make it easier to unload font sizes that are no longer needed.\nAn instance of MOAIFont may represent a dynamic or static font. Dynamic fonts are used to retrieve glyphs from a font file format on an as-needed basis. Static fonts have no associated font file format and therefore contain a fixed set of glyphs at runtime. For languages demanding very large character sets (such as Chinese), dynamic fonts are typically used. For languages where it is feasible to pre-render a full set of glyphs to texture (or bitmap fonts), static fonts may be used.\nMOAIFont orchestrates objects derived from MOAIFontReader and MOAIGlyphCacheBase to render glyphs into glyph sets. MOAIFontReader is responsible for interpreting the font file format (if any), retrieving glyph metrics (including kerning) and rendering glyphs to texture. MOAIGlyphCache is responsible for allocating textures to hold glyphs and for managing glyph placement within textures. For dynamic fonts, the typical setup uses MOAIFreeTypeFontReader and MOAIGlyphCache. For static fonts, there is usually no font reader; MOAIStaticGlyphCache is loaded directly from a serialized file and its texture memory is initialized with MOAIFont's setImage () command.\nAs mentioned, a single MOAIFont may be used to render multiple sizes of a font face. When glyphs need to be laid out or rendered, the font object will return a set of glyphs matching whatever size was requested. It is also possible to specify a default size that will be used if no size is requested for rendering or if no matching size is found. If no default size is set by the user, it will be set automatically the first time a specific size is requested.\nMOAIFont can also control how or if kerning tables are loaded when glyphs are being rendered. The default behavior is to load kerning information automatically. It is possible to prevent kerning information from being loaded. In this case, kerning tables may be loaded manually if so desired.",
childs = {
DEFAULT_FLAGS = {
type = "value"
},
FONT_AUTOLOAD_KERNING = {
type = "value"
},
getDefaultSize = {
type = "method",
description = "Requests the font's default size\n\n–> MOAIFont self\n<– number defaultSize",
args = "MOAIFont self",
returns = "number defaultSize",
valuetype = "number"
},
getFilename = {
type = "method",
description = "Returns the filename of the font.\n\n–> MOAIFont self\n<– string name",
args = "MOAIFont self",
returns = "string name",
valuetype = "string"
},
getFlags = {
type = "method",
description = "Returns the current flags.\n\n–> MOAIFont self\n<– number flags",
args = "MOAIFont self",
returns = "number flags",
valuetype = "number"
},
getImage = {
type = "method",
description = "Requests a 'glyph map image' from the glyph cache currently attached to the font. The glyph map image stitches together the texture pages used by the glyph cache to produce a single image that represents a snapshot of all of the texture memory being used by the font.\n\n–> MOAIFont self\n<– MOAIImage image",
args = "MOAIFont self",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
load = {
type = "method",
description = "Sets the filename of the font for use when loading glyphs.\n\n–> MOAIFont self\n–> string filename: The path to the font file to load.\n<– nil",
args = "(MOAIFont self, string filename)",
returns = "nil"
},
loadFromBMFont = {
type = "method",
description = "Sets the filename of the font for use when loading a BMFont.\n\n–> MOAIFont self\n–> string filename: The path to the BMFont file to load.\n[–> table textures: Table of preloaded textures.]\n<– nil",
args = "(MOAIFont self, string filename, [table textures])",
returns = "nil"
},
loadFromTTF = {
type = "method",
description = "Preloads a set of glyphs from a TTF or OTF. Included for backward compatibility. May be removed in a future release.\n\n–> MOAIFont self\n–> string filename\n–> string charcodes\n–> number points: The point size to be loaded from the TTF.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAIFont self, string filename, string charcodes, number points, [number dpi])",
returns = "nil"
},
preloadGlyphs = {
type = "method",
description = "Loads and caches glyphs for quick access later.\n\n–> MOAIFont self\n–> string charCodes: A string which defines the characters found in the this->\n–> number points: The point size to be rendered onto the internal texture.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAIFont self, string charCodes, number points, [number dpi])",
returns = "nil"
},
rebuildKerningTables = {
type = "method",
description = "Forces a full reload of the kerning tables for either a single glyph set within the font (if a size is specified) or for all glyph sets in the font.\n\nOverload:\n–> MOAIFont self\n<– nil\n\nOverload:\n–> MOAIFont self\n–> number points: The point size to be rendered onto the internal texture.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAIFont self, [number points, [number dpi]])",
returns = "nil"
},
setCache = {
type = "method",
description = "Attaches or clears the glyph cache associated with the font. The cache is an object derived from MOAIGlyphCacheBase and may be a dynamic cache that can allocate space for new glyphs on an as-needed basis or a static cache that only supports direct loading of glyphs and glyph textures through MOAIFont's setImage () command.\n\n–> MOAIFont self\n[–> MOAIGlyphCacheBase cache: Default value is nil.]\n<– nil",
args = "(MOAIFont self, [MOAIGlyphCacheBase cache])",
returns = "nil"
},
setDefaultSize = {
type = "method",
description = "Selects a glyph set size to use as the default size when no other size is specified by objects wishing to use MOAIFont to render text.\n\n–> MOAIFont self\n–> number points: The point size to be rendered onto the internal texture.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAIFont self, number points, [number dpi])",
returns = "nil"
},
setFlags = {
type = "method",
description = "Set flags to control font loading behavior. Right now the only supported flag is FONT_AUTOLOAD_KERNING which may be used to enable automatic loading of kern tables. This flag is initially true by default.\n\n–> MOAIFont self\n[–> number flags: Flags are FONT_AUTOLOAD_KERNING or DEFAULT_FLAGS. DEFAULT_FLAGS is the same as FONT_AUTOLOAD_KERNING. Alternatively, pass '0' to clear the flags.]\n<– nil",
args = "(MOAIFont self, [number flags])",
returns = "nil"
},
setImage = {
type = "method",
description = "Passes an image to the glyph cache currently attached to the font. The image will be used to recreate and initialize the texture memory managed by the glyph cache and used by the font. It will not affect any glyph entires that have already been laid out and stored in the glyph cache. If no cache is attached to the font, an instance of MOAIStaticGlyphCache will automatically be allocated.\n\n–> MOAIFont self\n–> MOAIImage image\n<– nil",
args = "(MOAIFont self, MOAIImage image)",
returns = "nil"
},
setReader = {
type = "method",
description = "Attaches or clears the MOAIFontReader associated with the font. MOAIFontReader is responsible for loading and rendering glyphs from a font file on demand. If you are using a static font and do not need a reader, set this field to nil.\n\n–> MOAIFont self\n[–> MOAIFontReader reader: Default value is nil.]\n<– nil",
args = "(MOAIFont self, [MOAIFontReader reader])",
returns = "nil"
}
}
},
MOAIFontReader = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIFoo = {
type = "class",
inherits = "MOAILuaObject",
description = "Example class for extending Moai using MOAILuaObject. Copy this object, rename it and add your own stuff. Just don't forget to register it with the runtime using the REGISTER_LUA_CLASS macro (see moaicore.cpp).",
childs = {
classHello = {
type = "function",
description = "Class (a.k.a. static) method. Prints the string 'MOAIFoo class foo!' to the console.\n\n<– nil",
args = "()",
returns = "nil"
},
instanceHello = {
type = "method",
description = "Prints the string 'MOAIFoo instance foo!' to the console.\n\n–> MOAIFoo self\n<– nil",
args = "MOAIFoo self",
returns = "nil"
}
}
},
MOAIFrameBuffer = {
type = "class",
inherits = "MOAIClearableView",
description = "MOAIFrameBuffer is responsible for drawing a list of MOAIRenderable objects. MOAIRenderable is the base class for any object that can be drawn. This includes MOAIProp and MOAILayer. To use MOAIFrameBuffer pass a table of MOAIRenderable objects to setRenderTable (). The table will usually be a stack of MOAILayer objects. The contents of the table will be rendered the next time a frame is drawn. Note that the table must be an array starting with index 1. Objects will be rendered counting from the base index until 'nil' is encountered. The render table may include other tables as entries. These must also be arrays indexed from 1.",
childs = {
getPerformanceDrawCount = {
type = "method",
description = 'Returns the number of draw calls last frame.\n\n–> MOAIFrameBuffer self\n<– number count: Number of underlying graphics "draw" calls last frame.',
args = "MOAIFrameBuffer self",
returns = "number count",
valuetype = "number"
},
getRenderTable = {
type = "method",
description = "Returns the table currently being used for rendering.\n\n–> MOAIFrameBuffer self\n<– table renderTable",
args = "MOAIFrameBuffer self",
returns = "table renderTable",
valuetype = "table"
},
grabNextFrame = {
type = "method",
description = "Save the next frame rendered to\n\n–> MOAIFrameBuffer self\n–> MOAIImage image: Image to save the backbuffer to\n–> function callback: The function to execute when the frame has been saved into the image specified\n<– nil",
args = "(MOAIFrameBuffer self, MOAIImage image, function callback)",
returns = "nil"
},
setRenderTable = {
type = "method",
description = "Sets the table to be used for rendering. This should be an array indexed from 1 consisting of MOAIRenderable objects and sub-tables. Objects will be rendered in order starting from index 1 and continuing until 'nil' is encountered.\n\n–> MOAIFrameBuffer self\n–> table renderTable\n<– nil",
args = "(MOAIFrameBuffer self, table renderTable)",
returns = "nil"
}
}
},
MOAIFrameBufferTexture = {
type = "class",
inherits = "MOAIFrameBuffer MOAITextureBase",
description = "This is an implementation of a frame buffer that may be attached to a MOAILayer for offscreen rendering. It is also a texture that may be bound and used like any other.",
childs = {
init = {
type = "method",
description = "Initializes frame buffer.\n\n–> MOAIFrameBufferTexture self\n–> number width\n–> number height\n[–> number colorFormat]\n[–> number depthFormat]\n[–> number stencilFormat]\n<– nil",
args = "(MOAIFrameBufferTexture self, number width, number height, [number colorFormat, [number depthFormat, [number stencilFormat]]])",
returns = "nil"
}
}
},
MOAIFreeTypeFontReader = {
type = "class",
inherits = "MOAIFontReader",
description = "Implementation of MOAIFontReader that based on FreeType 2. Can load and render TTF and OTF font files.",
childs = {}
},
MOAIGameCenterIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for iOS GameCenter functionality.",
childs = {
PLAYERSCOPE_FRIENDS = {
type = "value",
description = "Get leaderboard scores only for active player's friends."
},
PLAYERSCOPE_GLOBAL = {
type = "value",
description = "Get leaderboard scores for everyone."
},
TIMESCOPE_ALLTIME = {
type = "value",
description = "Get leaderboard scores for all time."
},
TIMESCOPE_TODAY = {
type = "value",
description = "Get leaderboard scores for today."
},
TIMESCOPE_WEEK = {
type = "value",
description = "Get leaderboard scores for the week."
}
}
},
MOAIGfxDevice = {
type = "class",
inherits = "MOAILuaObject",
description = "Interface to the graphics singleton.",
childs = {
EVENT_RESIZE = {
type = "value"
},
getFrameBuffer = {
type = "function",
description = "Returns the frame buffer associated with the device.\n\n<– MOAIFrameBuffer frameBuffer",
args = "()",
returns = "MOAIFrameBuffer frameBuffer",
valuetype = "MOAIFrameBuffer"
},
getMaxTextureUnits = {
type = "function",
description = "Returns the total number of texture units available on the device.\n\n<– number maxTextureUnits",
args = "()",
returns = "number maxTextureUnits",
valuetype = "number"
},
getViewSize = {
type = "function",
description = "Returns the width and height of the view\n\n<– number width\n<– number height",
args = "()",
returns = "(number width, number height)",
valuetype = "number"
},
isProgrammable = {
type = "function",
description = "Returns a boolean indicating whether or not Moai is running under the programmable pipeline.\n\n<– boolean isProgrammable",
args = "()",
returns = "boolean isProgrammable",
valuetype = "boolean"
},
setPenColor = {
type = "function",
description = "–> number r\n–> number g\n–> number b\n[–> number a: Default value is 1.]\n<– nil",
args = "(number r, number g, number b, [number a])",
returns = "nil"
},
setPenWidth = {
type = "function",
description = "–> number width\n<– nil",
args = "number width",
returns = "nil"
},
setPointSize = {
type = "function",
description = "–> number size\n<– nil",
args = "number size",
returns = "nil"
}
}
},
MOAIGfxQuad2D = {
type = "class",
inherits = "MOAIDeck",
description = "Single textured quad.",
childs = {
setQuad = {
type = "method",
description = "Set model space quad. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuad2D self\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuad2D self, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the model space dimensions of the quad.\n\n–> MOAIGfxQuad2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuad2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setUVQuad = {
type = "method",
description = "Set the UV space dimensions of the quad. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuad2D self\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuad2D self, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setUVRect = {
type = "method",
description = "Set the UV space dimensions of the quad.\n\n–> MOAIGfxQuad2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuad2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
transform = {
type = "method",
description = "Apply the given MOAITransform to all the vertices in the deck.\n\n–> MOAIGfxQuad2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuad2D self, MOAITransform transform)",
returns = "nil"
},
transformUV = {
type = "method",
description = "Apply the given MOAITransform to all the uv coordinates in the deck.\n\n–> MOAIGfxQuad2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuad2D self, MOAITransform transform)",
returns = "nil"
}
}
},
MOAIGfxQuadDeck2D = {
type = "class",
inherits = "MOAIDeck",
description = "Deck of textured quads.",
childs = {
reserve = {
type = "method",
description = "Set capacity of quad deck.\n\n–> MOAIGfxQuadDeck2D self\n–> number nQuads\n<– nil",
args = "(MOAIGfxQuadDeck2D self, number nQuads)",
returns = "nil"
},
setQuad = {
type = "method",
description = "Set model space quad given a valid deck index. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuadDeck2D self\n–> number idx: Index of the quad.\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuadDeck2D self, number idx, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set model space quad given a valid deck index and a rect.\n\n–> MOAIGfxQuadDeck2D self\n–> number idx: Index of the quad.\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuadDeck2D self, number idx, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setUVQuad = {
type = "method",
description = "Set UV space quad given a valid deck index. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuadDeck2D self\n–> number idx: Index of the quad.\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuadDeck2D self, number idx, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setUVRect = {
type = "method",
description = "Set UV space quad given a valid deck index and a rect.\n\n–> MOAIGfxQuadDeck2D self\n–> number idx: Index of the quad.\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuadDeck2D self, number idx, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
transform = {
type = "method",
description = "Apply the given MOAITransform to all the vertices in the deck.\n\n–> MOAIGfxQuadDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuadDeck2D self, MOAITransform transform)",
returns = "nil"
},
transformUV = {
type = "method",
description = "Apply the given MOAITransform to all the uv coordinates in the deck.\n\n–> MOAIGfxQuadDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuadDeck2D self, MOAITransform transform)",
returns = "nil"
}
}
},
MOAIGfxQuadListDeck2D = {
type = "class",
inherits = "MOAIDeck",
description = "Deck of lists of textured quads. UV and model space quads are specified independently and associated via pairs. Pairs are referenced by lists sequentially. There may be multiple pairs with the same UV/model quad indices if geometry is used in multiple lists.",
childs = {
reserveLists = {
type = "method",
description = "Reserve quad lists.\n\n–> MOAIGfxQuadListDeck2D self\n–> number nLists\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number nLists)",
returns = "nil"
},
reservePairs = {
type = "method",
description = "Reserve pairs.\n\n–> MOAIGfxQuadListDeck2D self\n–> number nPairs\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number nPairs)",
returns = "nil"
},
reserveQuads = {
type = "method",
description = "Reserve quads.\n\n–> MOAIGfxQuadListDeck2D self\n–> number nQuads\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number nQuads)",
returns = "nil"
},
reserveUVQuads = {
type = "method",
description = "Reserve UV quads.\n\n–> MOAIGfxQuadListDeck2D self\n–> number nUVQuads\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number nUVQuads)",
returns = "nil"
},
setList = {
type = "method",
description = "Initializes quad pair list at index. A list starts at the index of a pair and then continues sequentially for n pairs after. So a list with base 3 and a run of 4 would display pair 3, 4, 5, and 6.\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx\n–> number basePairID: The base pair of the list.\n–> number totalPairs: The run of the list - total pairs to display (including base).\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number basePairID, number totalPairs)",
returns = "nil"
},
setPair = {
type = "method",
description = "Associates a quad with its UV coordinates.\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx\n–> number uvQuadID\n–> number quadID\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number uvQuadID, number quadID)",
returns = "nil"
},
setQuad = {
type = "method",
description = "Set model space quad given a valid deck index. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx: Index of the quad.\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set model space quad given a valid deck index and a rect.\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx: Index of the quad.\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setUVQuad = {
type = "method",
description = "Set UV space quad given a valid deck index. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx: Index of the quad.\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setUVRect = {
type = "method",
description = "Set UV space quad given a valid deck index and a rect.\n\n–> MOAIGfxQuadListDeck2D self\n–> number idx: Index of the quad.\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, number idx, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
transform = {
type = "method",
description = "Apply the given MOAITransform to all the vertices in the deck.\n\n–> MOAIGfxQuadListDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, MOAITransform transform)",
returns = "nil"
},
transformUV = {
type = "method",
description = "Apply the given MOAITransform to all the uv coordinates in the deck.\n\n–> MOAIGfxQuadListDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAIGfxQuadListDeck2D self, MOAITransform transform)",
returns = "nil"
}
}
},
MOAIGfxResource = {
type = "class",
inherits = "MOAIGfxState",
description = "Base class for graphics resources owned by OpenGL. Implements resource lifecycle including restoration from a lost graphics context (if possible).",
childs = {
getAge = {
type = "method",
description = "Returns the 'age' of the graphics resource. The age is the number of times MOAIRenderMgr has rendered a scene since the resource was last bound. It is part of the render count, not a timestamp. This may change to be time-based in future releases.\n\n–> MOAIGfxResource self\n<– number age",
args = "MOAIGfxResource self",
returns = "number age",
valuetype = "number"
},
softRelease = {
type = "method",
description = "Attempt to release the resource. Generally this is used when responding to a memory warning from the system. A resource will only be released if it is renewable (i.e. has a renew callback or contains all information needed to reload the resources on demand). Using soft release can save an app in extreme memory circumstances, but may trigger reloads of resources during runtime which can significantly degrade performance.\n\n–> MOAIGfxResource self\n[–> number age: Release only if the texture hasn't been used in X frames.]\n<– boolean released: True if the texture was actually released.",
args = "(MOAIGfxResource self, [number age])",
returns = "boolean released",
valuetype = "boolean"
}
}
},
MOAIGfxState = {
type = "class",
inherits = "MOAILuaObject",
description = "Abstract base class for objects that represent changes to graphics state.",
childs = {}
},
MOAIGlobalEventSource = {
type = "class",
inherits = "MOAIEventSource",
description = "Derivation of MOAIEventSource for global Lua objects.",
childs = {}
},
MOAIGlyphCache = {
type = "class",
inherits = "MOAIGlyphCacheBase",
description = "This is the default implementation of a dynamic glyph cache. Right now it can only grow but support for reference counting glyphs and garbage collection will be added later.\nThe current implementation is set up in anticipation of garbage collection. If you use MOAIFont's getImage () to inspect the work of this cache you'll see that it is not as efficient in terms of texture use as it could be - glyphs are grouped by size, all glyphs for a given face size are given the same height and layout is orientated around rows. All of this will make it much easier to replace individual glyph slots as the set of glyphs that needs to be in memory changes. That said, we may offer an alternative dynamic cache implementation that attempts a more compact use of texture space, the tradeoff being that there won't be any garbage collection.\nThis implementation of the dynamic glyph cache does not implement setImage ().\nOf course, you can also derive your own implementation from MOAIGlyphCacheBase.",
childs = {}
},
MOAIGlyphCacheBase = {
type = "class",
inherits = "MOAILuaObject",
description = "Base class for implementations of glyph caches. A glyph cache is responsible for allocating textures to hold rendered glyphs and for placing individuals glyphs on those textures.\nEven though the glyph cache is responsible for placing glyphs on textures, the glyph cache does not have to keep track of glyph metrics. Glyph metrics are stored independently by the font. This means that glyph caches with equivalent textures may be swapped out for use with the same font.",
childs = {
setColorFormat = {
type = "method",
description = "The color format may be used by dynamic cache implementations when allocating new textures.\n\n–> MOAIGlyphCacheBase self\n–> number colorFmt: One of MOAIImage.COLOR_FMT_A_8, MOAIImage.COLOR_FMT_RGB_888, MOAIImage.COLOR_FMT_RGB_565, MOAIImage.COLOR_FMT_RGBA_5551, MOAIImage.COLOR_FMT_RGBA_4444, COLOR_FMT_RGBA_8888\n<– nil",
args = "(MOAIGlyphCacheBase self, number colorFmt)",
returns = "nil"
}
}
},
MOAIGrid = {
type = "class",
inherits = "MOAIGridSpace",
description = "Grid data object. Grid cells are indexed starting and (1,1). Grid indices will wrap if out of range.",
childs = {
clearTileFlags = {
type = "method",
description = "Clears bits specified in mask.\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n–> number mask\n<– nil",
args = "(MOAIGrid self, number xTile, number yTile, number mask)",
returns = "nil"
},
fill = {
type = "method",
description = "Set all tiles to a single value\n\n–> MOAIGrid self\n–> number value\n<– nil",
args = "(MOAIGrid self, number value)",
returns = "nil"
},
getTile = {
type = "method",
description = "Returns the value of a given tile.\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n<– number tile",
args = "(MOAIGrid self, number xTile, number yTile)",
returns = "number tile",
valuetype = "number"
},
getTileFlags = {
type = "method",
description = "Returns the masked value of a given tile.\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n–> number mask\n<– number tile",
args = "(MOAIGrid self, number xTile, number yTile, number mask)",
returns = "number tile",
valuetype = "number"
},
setRow = {
type = "method",
description = "Initializes a grid row given a variable argument list of values.\n\n–> MOAIGrid self\n–> number row\n–> ... values\n<– nil",
args = "(MOAIGrid self, number row, ... values)",
returns = "nil"
},
setTile = {
type = "method",
description = "Sets the value of a given tile\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n–> number value\n<– nil",
args = "(MOAIGrid self, number xTile, number yTile, number value)",
returns = "nil"
},
setTileFlags = {
type = "method",
description = "Sets a tile's flags given a mask.\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n–> number mask\n<– nil",
args = "(MOAIGrid self, number xTile, number yTile, number mask)",
returns = "nil"
},
streamTilesIn = {
type = "method",
description = "Reads tiles directly from a stream. Call this only after initializing the grid. Only the content of the tiles buffer is read.\n\n–> MOAIGrid self\n–> MOAIStream stream\n<– number bytesRead",
args = "(MOAIGrid self, MOAIStream stream)",
returns = "number bytesRead",
valuetype = "number"
},
streamTilesOut = {
type = "method",
description = "Writes tiles directly to a stream. Only the content of the tiles buffer is written.\n\n–> MOAIGrid self\n–> MOAIStream stream\n<– number bytesWritten",
args = "(MOAIGrid self, MOAIStream stream)",
returns = "number bytesWritten",
valuetype = "number"
},
toggleTileFlags = {
type = "method",
description = "Toggles a tile's flags given a mask.\n\n–> MOAIGrid self\n–> number xTile\n–> number yTile\n–> number mask\n<– nil",
args = "(MOAIGrid self, number xTile, number yTile, number mask)",
returns = "nil"
}
}
},
MOAIGridDeck2D = {
type = "class",
inherits = "MOAIDeck",
description = "This deck renders 'brushes' which are sampled from a tile map. The tile map is specified by the attached grid, deck and remapper. Each 'brush' defines a rectangle of tiles to draw and an offset.",
childs = {
reserveBrushes = {
type = "method",
description = "Set capacity of grid deck.\n\n–> MOAIGridDeck2D self\n–> number nBrushes\n<– nil",
args = "(MOAIGridDeck2D self, number nBrushes)",
returns = "nil"
},
setBrush = {
type = "method",
description = "Initializes a brush.\n\n–> MOAIGridDeck2D self\n–> number idx: Index of the brush.\n–> number xTile\n–> number yTile\n–> number width\n–> number height\n[–> number xOff: Default value is 0.]\n[–> number yOff: Default value is 0.]\n<– nil",
args = "(MOAIGridDeck2D self, number idx, number xTile, number yTile, number width, number height, [number xOff, [number yOff]])",
returns = "nil"
},
setDeck = {
type = "method",
description = "Sets or clears the deck to be indexed by the grid.\n\n–> MOAIGridDeck2D self\n[–> MOAIDeck deck: Default value is nil.]\n<– nil",
args = "(MOAIGridDeck2D self, [MOAIDeck deck])",
returns = "nil"
},
setGrid = {
type = "method",
description = "Sets or clears the grid to be sampled by the brushes.\n\n–> MOAIGridDeck2D self\n[–> MOAIGrid grid: Default value is nil.]\n<– nil",
args = "(MOAIGridDeck2D self, [MOAIGrid grid])",
returns = "nil"
},
setRemapper = {
type = "method",
description = "Sets or clears the remapper (for remapping index values held in the grid).\n\n–> MOAIGridDeck2D self\n[–> MOAIDeckRemapper remapper: Default value is nil.]\n<– nil",
args = "(MOAIGridDeck2D self, [MOAIDeckRemapper remapper])",
returns = "nil"
}
}
},
MOAIGridPathGraph = {
type = "class",
inherits = "MOAIPathGraph MOAILuaObject",
description = "Pathfinder graph adapter for MOAIGrid.",
childs = {
setGrid = {
type = "method",
description = "Set graph data to use for pathfinding.\n\n–> MOAIGridPathGraph self\n[–> MOAIGrid grid: Default value is nil.]\n<– nil",
args = "(MOAIGridPathGraph self, [MOAIGrid grid])",
returns = "nil"
}
}
},
MOAIGridSpace = {
type = "class",
inherits = "MOAILuaObject",
description = "Represents spatial configuration of a grid. The grid is made up of cells. Inside of each cell is a tile. The tile can be larger or smaller than the cell and also offset from the cell. By default, tiles are the same size of their cells and are no offset.",
childs = {
DIAMOND_SHAPE = {
type = "value"
},
HEX_SHAPE = {
type = "value"
},
OBLIQUE_SHAPE = {
type = "value"
},
SQUARE_SHAPE = {
type = "value"
},
TILE_BOTTOM_CENTER = {
type = "value"
},
TILE_CENTER = {
type = "value"
},
TILE_LEFT_BOTTOM = {
type = "value"
},
TILE_LEFT_CENTER = {
type = "value"
},
TILE_LEFT_TOP = {
type = "value"
},
TILE_RIGHT_BOTTOM = {
type = "value"
},
TILE_RIGHT_CENTER = {
type = "value"
},
TILE_RIGHT_TOP = {
type = "value"
},
TILE_TOP_CENTER = {
type = "value"
},
TILE_HIDE = {
type = "value"
},
TILE_X_FLIP = {
type = "value"
},
TILE_XY_FLIP = {
type = "value"
},
TILE_Y_FLIP = {
type = "value"
},
cellAddrToCoord = {
type = "method",
description = "Returns the coordinate of a cell given an address.\n\n–> MOAIGridSpace self\n–> number cellAddr\n<– number xTile\n<– number yTile",
args = "(MOAIGridSpace self, number cellAddr)",
returns = "(number xTile, number yTile)",
valuetype = "number"
},
getCellAddr = {
type = "method",
description = "Returns the address of a cell given a coordinate (in tiles).\n\n–> MOAIGridSpace self\n–> number xTile\n–> number yTile\n<– number cellAddr",
args = "(MOAIGridSpace self, number xTile, number yTile)",
returns = "number cellAddr",
valuetype = "number"
},
getCellSize = {
type = "method",
description = "Returns the dimensions of a single grid cell.\n\n–> MOAIGridSpace self\n<– number width\n<– number height",
args = "MOAIGridSpace self",
returns = "(number width, number height)",
valuetype = "number"
},
getOffset = {
type = "method",
description = "Returns the offset of tiles from cells.\n\n–> MOAIGridSpace self\n<– number xOff\n<– number yOff",
args = "MOAIGridSpace self",
returns = "(number xOff, number yOff)",
valuetype = "number"
},
getSize = {
type = "method",
description = "Returns the dimensions of the grid (in tiles).\n\n–> MOAIGridSpace self\n<– number width\n<– number height",
args = "MOAIGridSpace self",
returns = "(number width, number height)",
valuetype = "number"
},
getTileLoc = {
type = "method",
description = "Returns the grid space coordinate of the tile. The optional 'position' flag determines the location of the coordinate within the tile.\n\n–> MOAIGridSpace self\n–> number xTile\n–> number yTile\n[–> number position: See MOAIGridSpace for list of positions. Default it MOAIGridSpace.TILE_CENTER.]\n<– number x\n<– number y",
args = "(MOAIGridSpace self, number xTile, number yTile, [number position])",
returns = "(number x, number y)",
valuetype = "number"
},
getTileSize = {
type = "method",
description = "Returns the dimensions of a single grid tile.\n\n–> MOAIGridSpace self\n<– number width\n<– number height",
args = "MOAIGridSpace self",
returns = "(number width, number height)",
valuetype = "number"
},
initDiamondGrid = {
type = "method",
description = "Initialize a grid with hexagonal tiles.\n\n–> MOAIGridSpace self\n–> number width\n–> number height\n[–> number tileWidth: Default value is 1.]\n[–> number tileHeight: Default value is 1.]\n[–> number xGutter: Default value is 0.]\n[–> number yGutter: Default value is 0.]\n<– nil",
args = "(MOAIGridSpace self, number width, number height, [number tileWidth, [number tileHeight, [number xGutter, [number yGutter]]]])",
returns = "nil"
},
initHexGrid = {
type = "method",
description = "Initialize a grid with hexagonal tiles.\n\n–> MOAIGridSpace self\n–> number width\n–> number height\n[–> number radius: Default value is 1.]\n[–> number xGutter: Default value is 0.]\n[–> number yGutter: Default value is 0.]\n<– nil",
args = "(MOAIGridSpace self, number width, number height, [number radius, [number xGutter, [number yGutter]]])",
returns = "nil"
},
initObliqueGrid = {
type = "method",
description = "Initialize a grid with oblique tiles.\n\n–> MOAIGridSpace self\n–> number width\n–> number height\n[–> number tileWidth: Default value is 1.]\n[–> number tileHeight: Default value is 1.]\n[–> number xGutter: Default value is 0.]\n[–> number yGutter: Default value is 0.]\n<– nil",
args = "(MOAIGridSpace self, number width, number height, [number tileWidth, [number tileHeight, [number xGutter, [number yGutter]]]])",
returns = "nil"
},
initRectGrid = {
type = "method",
description = "Initialize a grid with rectangular tiles.\n\n–> MOAIGridSpace self\n–> number width\n–> number height\n[–> number tileWidth: Default value is 1.]\n[–> number tileHeight: Default value is 1.]\n[–> number xGutter: Default value is 0.]\n[–> number yGutter: Default value is 0.]\n<– nil",
args = "(MOAIGridSpace self, number width, number height, [number tileWidth, [number tileHeight, [number xGutter, [number yGutter]]]])",
returns = "nil"
},
locToCellAddr = {
type = "method",
description = "Returns the address of a cell given a a coordinate in grid space.\n\n–> MOAIGridSpace self\n–> number x\n–> number y\n<– number cellAddr",
args = "(MOAIGridSpace self, number x, number y)",
returns = "number cellAddr",
valuetype = "number"
},
locToCoord = {
type = "method",
description = "Transforms a coordinate in grid space into a tile index.\n\n–> MOAIGridSpace self\n–> number x\n–> number y\n<– number xTile\n<– number yTile",
args = "(MOAIGridSpace self, number x, number y)",
returns = "(number xTile, number yTile)",
valuetype = "number"
},
setRepeat = {
type = "method",
description = "Repeats a grid indexer along X or Y. Only used when a grid is attached.\n\n–> MOAIGridSpace self\n[–> boolean repeatX: Default value is true.]\n[–> boolean repeatY: Default value is repeatX.]\n<– nil",
args = "(MOAIGridSpace self, [boolean repeatX, [boolean repeatY]])",
returns = "nil"
},
setShape = {
type = "method",
description = "Set the shape of the grid tiles.\n\n–> MOAIGridSpace self\n[–> number shape: One of MOAIGridSpace.RECT_SHAPE, MOAIGridSpace.DIAMOND_SHAPE, MOAIGridSpace.OBLIQUE_SHAPE, MOAIGridSpace.HEX_SHAPE. Default value is MOAIGridSpace.RECT_SHAPE.]\n<– nil",
args = "(MOAIGridSpace self, [number shape])",
returns = "nil"
},
setSize = {
type = "method",
description = "Initializes dimensions of grid and reserves storage for tiles.\n\n–> MOAIGridSpace self\n–> number width\n–> number height\n[–> number cellWidth: Default value is 1.]\n[–> number cellHeight: Default value is 1.]\n[–> number xOff: X offset of the tile from the cell.]\n[–> number yOff: Y offset of the tile from the cell.]\n[–> number tileWidth: Default value is cellWidth.]\n[–> number tileHeight: Default value is cellHeight.]\n<– nil",
args = "(MOAIGridSpace self, number width, number height, [number cellWidth, [number cellHeight, [number xOff, [number yOff, [number tileWidth, [number tileHeight]]]]]])",
returns = "nil"
},
wrapCoord = {
type = "method",
description = "Wraps a tile index to the range of the grid.\n\n–> MOAIGridSpace self\n–> number xTile\n–> number yTile\n<– number xTile\n<– number yTile",
args = "(MOAIGridSpace self, number xTile, number yTile)",
returns = "(number xTile, number yTile)",
valuetype = "number"
}
}
},
MOAIHarness = {
type = "class",
inherits = "MOAILuaObject",
description = "Internal debugging and hooking class.",
childs = {}
},
MOAIHashWriter = {
type = "class",
inherits = "MOAIStream",
description = "MOAIHashWriter may be attached to another stream for the purpose of computing a hash while writing data to the other stream. Currently only MD5 and SHA256 are available.",
childs = {
close = {
type = "method",
description = "Flush any remaining buffered data and detach the target stream. (This only detaches the target from the formatter; it does not also close the target stream). Return the hash as a hex string.\n\n–> MOAIHashWriter self\n<– string hash",
args = "MOAIHashWriter self",
returns = "string hash",
valuetype = "string"
},
openAdler32 = {
type = "method",
description = "Open a Adler32 hash stream for writing. (i.e. compute Adler32 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openCRC32 = {
type = "method",
description = "Open a CRC32 hash stream for writing. (i.e. compute CRC32 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openCRC32b = {
type = "method",
description = "Open a CRC32b hash stream for writing. (i.e. compute CRC32b hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openMD5 = {
type = "method",
description = "Open a MD5 hash stream for writing. (i.e. compute MD5 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openSHA1 = {
type = "method",
description = "Open a SHA1 hash stream for writing. (i.e. compute SHA1 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openSHA224 = {
type = "method",
description = "Open a SHA224 hash stream for writing. (i.e. compute SHA256 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openSHA256 = {
type = "method",
description = "Open a SHA256 hash stream for writing. (i.e. compute SHA256 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openSHA384 = {
type = "method",
description = "Open a SHA384 hash stream for writing. (i.e. compute SHA256 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openSHA512 = {
type = "method",
description = "Open a SHA512 hash stream for writing. (i.e. compute SHA256 hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
},
openWhirlpool = {
type = "method",
description = "Open a Whirlpool hash stream for writing. (i.e. compute Whirlpool hash of data while writing)\n\n–> MOAIHashWriter self\n[–> MOAIStream target]\n<– boolean success",
args = "(MOAIHashWriter self, [MOAIStream target])",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIHttpTaskBase = {
type = "class",
inherits = "MOAILuaObject",
description = "Object for performing asynchronous HTTP/HTTPS tasks.",
childs = {
HTTP_DELETE = {
type = "value"
},
HTTP_GET = {
type = "value"
},
HTTP_HEAD = {
type = "value"
},
HTTP_POST = {
type = "value"
},
HTTP_PUT = {
type = "value"
},
getProgress = {
type = "method",
description = "Returns the progress of the download.\n\n–> MOAIHttpTaskBase self\n<– number progress: the percentage the download has left ( form 0.0 to 1.0 )",
args = "MOAIHttpTaskBase self",
returns = "number progress",
valuetype = "number"
},
getResponseCode = {
type = "method",
description = "Returns the response code returned by the server after a httpPost or httpGet call.\n\n–> MOAIHttpTaskBase self\n<– number code: The numeric response code returned by the server.",
args = "MOAIHttpTaskBase self",
returns = "number code",
valuetype = "number"
},
getResponseHeader = {
type = "method",
description = "Returns the response header given its name, or nil if it wasn't provided by the server. Header names are case-insensitive and if multiple responses are given, they will be concatenated with a comma separating the values.\n\n–> MOAIHttpTaskBase self\n–> string header: The name of the header to return (case-insensitive).\n<– string response: The response given by the server or nil if none was specified.",
args = "(MOAIHttpTaskBase self, string header)",
returns = "string response",
valuetype = "string"
},
getSize = {
type = "method",
description = "Returns the size of the string obtained from a httpPost or httpGet call.\n\n–> MOAIHttpTaskBase self\n<– number size: The string size. If the call found nothing, this will return the value zero (not nil).",
args = "MOAIHttpTaskBase self",
returns = "number size",
valuetype = "number"
},
getString = {
type = "method",
description = "Returns the text obtained from a httpPost or httpGet call.\n\n–> MOAIHttpTaskBase self\n<– string text: The text string.",
args = "MOAIHttpTaskBase self",
returns = "string text",
valuetype = "string"
},
httpGet = {
type = "method",
description = 'Sends an API call to the server for downloading data. The callback function (from setCallback) will run when the call is complete, i.e. this action is asynchronous and returns almost instantly.\n\n–> MOAIHttpTaskBase self\n–> string url: The URL on which to perform the GET request.\n[–> string useragent: Default value is "Moai SDK beta; support@getmoai.com"]\n[–> boolean verbose]\n[–> boolean blocking: Synchronous operation; block execution until complete. Default value is false.]\n<– nil',
args = "(MOAIHttpTaskBase self, string url, [string useragent, [boolean verbose, [boolean blocking]]])",
returns = "nil"
},
httpPost = {
type = "method",
description = 'Sends an API call to the server for downloading data. The callback function (from setCallback) will run when the call is complete, i.e. this action is asynchronous and returns almost instantly.\n\nOverload:\n–> MOAIHttpTaskBase self\n–> string url: The URL on which to perform the GET request.\n[–> string data: The string containing text to send as POST data.]\n[–> string useragent: Default value is "Moai SDK beta; support@getmoai.com"]\n[–> boolean verbose]\n[–> boolean blocking: Synchronous operation; block execution until complete. Default value is false.]\n<– nil\n\nOverload:\n–> MOAIHttpTaskBase self\n–> string url: The URL on which to perform the GET request.\n[–> MOAIDataBuffer data: A MOAIDataBuffer object to send as POST data.]\n[–> string useragent]\n[–> boolean verbose]\n[–> boolean blocking: Synchronous operation; block execution until complete. Default value is false.]\n<– nil',
args = "(MOAIHttpTaskBase self, string url, [(string data | MOAIDataBuffer data), [string useragent, [boolean verbose, [boolean blocking]]]])",
returns = "nil"
},
isBusy = {
type = "method",
description = "Returns whether or not the task is busy.\n\n–> MOAIHttpTaskBase self\n<– boolean busy",
args = "MOAIHttpTaskBase self",
returns = "boolean busy",
valuetype = "boolean"
},
parseXml = {
type = "method",
description = "Parses the text data returned from a httpGet or httpPost operation as XML and then returns a MOAIXmlParser with the XML content initialized.\n\n–> MOAIHttpTaskBase self\n<– MOAIXmlParser parser: The MOAIXmlParser which has parsed the returned data.",
args = "MOAIHttpTaskBase self",
returns = "MOAIXmlParser parser",
valuetype = "MOAIXmlParser"
},
performAsync = {
type = "method",
description = "Perform the HTTP task asynchronously.\n\n–> MOAIHttpTaskBase self\n<– nil",
args = "MOAIHttpTaskBase self",
returns = "nil"
},
performSync = {
type = "method",
description = "Perform the HTTP task synchronously ( blocking).\n\n–> MOAIHttpTaskBase self\n<– nil",
args = "MOAIHttpTaskBase self",
returns = "nil"
},
setBody = {
type = "method",
description = "Sets the body for a POST or PUT.\n\nOverload:\n–> MOAIHttpTaskBase self\n[–> string data: The string containing text to send as POST data.]\n<– nil\n\nOverload:\n–> MOAIHttpTaskBase self\n[–> MOAIDataBuffer data: A MOAIDataBuffer object to send as POST data.]\n<– nil",
args = "(MOAIHttpTaskBase self, [string data | MOAIDataBuffer data])",
returns = "nil"
},
setCallback = {
type = "method",
description = "Sets the callback function used when a request is complete.\n\n–> MOAIHttpTaskBase self\n–> function callback: The function to execute when the HTTP request is complete. The MOAIHttpTaskBase is passed as the first argument.\n<– nil",
args = "(MOAIHttpTaskBase self, function callback)",
returns = "nil"
},
setCookieDst = {
type = "method",
description = "Sets the file to save the cookies for this HTTP request\n\n–> MOAIHttpTaskBase self\n–> string filename: name and path of the file to save the cookies to\n<– nil",
args = "(MOAIHttpTaskBase self, string filename)",
returns = "nil"
},
setCookieSrc = {
type = "method",
description = "Sets the file to read the cookies for this HTTP request\n\n–> MOAIHttpTaskBase self\n–> string filename: name and path of the file to read the cookies from\n<– nil",
args = "(MOAIHttpTaskBase self, string filename)",
returns = "nil"
},
setFailOnError = {
type = "method",
description = "Sets whether or not curl calls will fail if the HTTP status code is above 400\n\n–> MOAIHttpTaskBase self\n–> boolean enable\n<– nil",
args = "(MOAIHttpTaskBase self, boolean enable)",
returns = "nil"
},
setFollowRedirects = {
type = "method",
description = "Sets whether or not curl should follow HTTP header redirects.\n\n–> MOAIHttpTaskBase self\n–> boolean follow\n<– nil",
args = "(MOAIHttpTaskBase self, boolean follow)",
returns = "nil"
},
setHeader = {
type = "method",
description = 'Sets a custom header field. May be used to override default headers.\n\n–> MOAIHttpTaskBase self\n–> string key\n[–> string value: Default is "".]\n<– nil',
args = "(MOAIHttpTaskBase self, string key, [string value])",
returns = "nil"
},
setStream = {
type = "method",
description = "Sets a custom stream to read data into.\n\n–> MOAIHttpTaskBase self\n–> MOAIStream stream\n<– nil",
args = "(MOAIHttpTaskBase self, MOAIStream stream)",
returns = "nil"
},
setTimeout = {
type = "method",
description = "Sets the timeout for the task.\n\n–> MOAIHttpTaskBase self\n–> number timeout\n<– nil",
args = "(MOAIHttpTaskBase self, number timeout)",
returns = "nil"
},
setUrl = {
type = "method",
description = "Sets the URL for the task.\n\n–> MOAIHttpTaskBase self\n–> string url\n<– nil",
args = "(MOAIHttpTaskBase self, string url)",
returns = "nil"
},
setUserAgent = {
type = "method",
description = "Sets the 'useragent' header for the task.\n\n–> MOAIHttpTaskBase self\n[–> string useragent: Default value is \"Moai SDK beta; support@getmoai.com\"]\n<– nil",
args = "(MOAIHttpTaskBase self, [string useragent])",
returns = "nil"
},
setVerb = {
type = "method",
description = "Sets the HTTP verb.\n\n–> MOAIHttpTaskBase self\n–> number verb: One of MOAIHttpTaskBase.HTTP_GET, MOAIHttpTaskBase.HTTP_HEAD, MOAIHttpTaskBase.HTTP_POST, MOAIHttpTaskBase.HTTP_PUT, MOAIHttpTaskBase.HTTP_DELETE\n<– nil",
args = "(MOAIHttpTaskBase self, number verb)",
returns = "nil"
},
setVerbose = {
type = "method",
description = "Sets the task implementation to print out debug information (if any).\n\n–> MOAIHttpTaskBase self\n[–> boolean verbose: Default value is false.]\n<– nil",
args = "(MOAIHttpTaskBase self, [boolean verbose])",
returns = "nil"
}
}
},
MOAIHttpTaskCurl = {
type = "class",
inherits = "MOAIHttpTaskBase",
description = "Implementation of MOAIHttpTask based on libcurl.",
childs = {}
},
MOAIHttpTaskNaCl = {
type = "class",
inherits = "MOAIHttpTaskBase",
description = "Implementation of MOAIHttpTask based on NaCl.",
childs = {}
},
MOAIHttpTaskNSURL = {
type = "class",
inherits = "MOAIHttpTaskBase",
description = "Implementation of MOAIHttpTask based on libcurl.",
childs = {}
},
MOAIImage = {
type = "class",
inherits = "MOAILuaObject",
description = "Image/bitmap class.",
childs = {
FILTER_LINEAR = {
type = "value"
},
FILTER_NEAREST = {
type = "value"
},
COLOR_FMT_A_8 = {
type = "value"
},
COLOR_FMT_RGB_565 = {
type = "value"
},
COLOR_FMT_RGB_888 = {
type = "value"
},
COLOR_FMT_RGBA_4444 = {
type = "value"
},
COLOR_FMT_RGBA_5551 = {
type = "value"
},
COLOR_FMT_RGBA_8888 = {
type = "value"
},
PIXEL_FMT_INDEX_4 = {
type = "value"
},
PIXEL_FMT_INDEX_8 = {
type = "value"
},
PIXEL_FMT_TRUECOLOR = {
type = "value"
},
POW_TWO = {
type = "value"
},
PREMULTIPLY_ALPHA = {
type = "value"
},
QUANTIZE = {
type = "value"
},
TRUECOLOR = {
type = "value"
},
bleedRect = {
type = "method",
description = "'Bleeds' the interior of the rectangle out by one pixel.\n\n–> MOAIImage self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIImage self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
compare = {
type = "method",
description = "Compares the image to another image.\n\n–> MOAIImage self\n–> MOAIImage other\n<– boolean areEqual: A value indicating whether the images are equal.",
args = "(MOAIImage self, MOAIImage other)",
returns = "boolean areEqual",
valuetype = "boolean"
},
convertColors = {
type = "method",
description = "Return a copy of the image with a new color format. Not all provided formats are supported by OpenGL.\n\n–> MOAIImage self\n–> number colorFmt: One of MOAIImage.COLOR_FMT_A_8, MOAIImage.COLOR_FMT_RGB_888, MOAIImage.COLOR_FMT_RGB_565, MOAIImage.COLOR_FMT_RGBA_5551, MOAIImage.COLOR_FMT_RGBA_4444, COLOR_FMT_RGBA_8888\n<– MOAIImage image: Copy of the image initialized with given format.",
args = "(MOAIImage self, number colorFmt)",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
convertToGrayScale = {
type = "method",
description = "Convert image to grayscale.\n\n–> MOAIImage self\n<– nil",
args = "MOAIImage self",
returns = "nil"
},
copy = {
type = "method",
description = "Copies an image.\n\n–> MOAIImage self\n<– MOAIImage image: Copy of the image.",
args = "MOAIImage self",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
copyBits = {
type = "method",
description = "Copy a section of one image to another.\n\n–> MOAIImage self\n–> MOAIImage source: Source image.\n–> number srcX: X location in source image.\n–> number srcY: Y location in source image.\n–> number destX: X location in destination image.\n–> number destY: Y location in destination image.\n–> number width: Width of section to copy.\n–> number height: Height of section to copy.\n<– nil",
args = "(MOAIImage self, MOAIImage source, number srcX, number srcY, number destX, number destY, number width, number height)",
returns = "nil"
},
copyRect = {
type = "method",
description = "Copy a section of one image to another. Accepts two rectangles. Rectangles may be of different size and proportion. Section of image may also be flipped horizontally or vertically by reversing min/max of either rectangle.\n\n–> MOAIImage self\n–> MOAIImage source: Source image.\n–> number srcXMin\n–> number srcYMin\n–> number srcXMax\n–> number srcYMax\n–> number destXMin\n–> number destYMin\n[–> number destXMax: Default value is destXMin + srcXMax - srcXMin;]\n[–> number destYMax: Default value is destYMin + srcYMax - srcYMin;]\n[–> number filter: One of MOAIImage.FILTER_LINEAR, MOAIImage.FILTER_NEAREST. Default value is MOAIImage.FILTER_LINEAR.]\n<– nil",
args = "(MOAIImage self, MOAIImage source, number srcXMin, number srcYMin, number srcXMax, number srcYMax, number destXMin, number destYMin, [number destXMax, [number destYMax, [number filter]]])",
returns = "nil"
},
fillCircle = {
type = "function",
description = "Draw a filled circle.\n\n–> number x\n–> number y\n–> number radius\n[–> number r: Default value is 0.]\n[–> number g: Default value is 0.]\n[–> number b: Default value is 0.]\n[–> number a: Default value is 0.]\n<– nil",
args = "(number x, number y, number radius, [number r, [number g, [number b, [number a]]]])",
returns = "nil"
},
fillRect = {
type = "method",
description = "Fill a rectangle in the image with a solid color.\n\n–> MOAIImage self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n[–> number r: Default value is 0.]\n[–> number g: Default value is 0.]\n[–> number b: Default value is 0.]\n[–> number a: Default value is 0.]\n<– nil",
args = "(MOAIImage self, number xMin, number yMin, number xMax, number yMax, [number r, [number g, [number b, [number a]]]])",
returns = "nil"
},
getColor32 = {
type = "method",
description = "Returns a 32-bit packed RGBA value from the image for a given pixel coordinate.\n\n–> MOAIImage self\n–> number x\n–> number y\n<– number color",
args = "(MOAIImage self, number x, number y)",
returns = "number color",
valuetype = "number"
},
getFormat = {
type = "method",
description = "Returns the color format of the image.\n\n–> MOAIImage self\n<– number colorFormat",
args = "MOAIImage self",
returns = "number colorFormat",
valuetype = "number"
},
getRGBA = {
type = "method",
description = "Returns an RGBA color as four floating point values.\n\n–> MOAIImage self\n–> number x\n–> number y\n<– number r\n<– number g\n<– number b\n<– number a",
args = "(MOAIImage self, number x, number y)",
returns = "(number r, number g, number b, number a)",
valuetype = "number"
},
getSize = {
type = "method",
description = "Returns the width and height of the image.\n\n–> MOAIImage self\n<– number width\n<– number height",
args = "MOAIImage self",
returns = "(number width, number height)",
valuetype = "number"
},
init = {
type = "method",
description = "Initializes the image with a width, height and color format.\n\n–> MOAIImage self\n–> number width\n–> number height\n[–> number colorFmt: One of MOAIImage.COLOR_FMT_A_8, MOAIImage.COLOR_FMT_RGB_888, MOAIImage.COLOR_FMT_RGB_565, MOAIImage.COLOR_FMT_RGBA_5551, MOAIImage.COLOR_FMT_RGBA_4444, MOAIImage.COLOR_FMT_RGBA_8888. Default value is MOAIImage.COLOR_FMT_RGBA_8888.]\n<– nil",
args = "(MOAIImage self, number width, number height, [number colorFmt])",
returns = "nil"
},
load = {
type = "method",
description = "Loads an image from a PNG.\n\n–> MOAIImage self\n–> string filename\n[–> number transform: One of MOAIImage.POW_TWO, One of MOAIImage.QUANTIZE, One of MOAIImage.TRUECOLOR, One of MOAIImage.PREMULTIPLY_ALPHA]\n<– nil",
args = "(MOAIImage self, string filename, [number transform])",
returns = "nil"
},
loadFromBuffer = {
type = "method",
description = "Loads an image from a buffer.\n\n–> MOAIImage self\n–> MOAIDataBuffer buffer: Buffer containing the image\n[–> number transform: One of MOAIImage.POW_TWO, One of MOAIImage.QUANTIZE, One of MOAIImage.TRUECOLOR, One of MOAIImage.PREMULTIPLY_ALPHA]\n<– nil",
args = "(MOAIImage self, MOAIDataBuffer buffer, [number transform])",
returns = "nil"
},
padToPow2 = {
type = "method",
description = "Copies an image and returns a new image padded to the next power of 2 along each dimension. Original image will be in the upper left hand corner of the new image.\n\n–> MOAIImage self\n<– MOAIImage image: Copy of the image padded to the next nearest power of two along each dimension.",
args = "MOAIImage self",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
resize = {
type = "method",
description = "Copies the image to an image with a new size.\n\n–> MOAIImage self\n–> number width: New width of the image.\n–> number height: New height of the image.\n[–> number filter: One of MOAIImage.FILTER_LINEAR, MOAIImage.FILTER_NEAREST. Default value is MOAIImage.FILTER_LINEAR.]\n<– MOAIImage image",
args = "(MOAIImage self, number width, number height, [number filter])",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
resizeCanvas = {
type = "method",
description = "Copies the image to a canvas with a new size. If the canvas is larger than the original image, the extra pixels will be initialized with 0. Pass in a new frame or just a new width and height. Negative values are permitted for the frame.\n\nOverload:\n–> MOAIImage self\n–> number width: New width of the image.\n–> number height: New height of the image.\n<– MOAIImage image\n\nOverload:\n–> MOAIImage self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– MOAIImage image",
args = "(MOAIImage self, ((number width, number height) | (number xMin, number yMin, number xMax, number yMax)))",
returns = "MOAIImage image",
valuetype = "MOAIImage"
},
setColor32 = {
type = "method",
description = "Sets 32-bit the packed RGBA value for a given pixel coordinate. Parameter will be converted to the native format of the image.\n\n–> MOAIImage self\n–> number x\n–> number y\n–> number color\n<– nil",
args = "(MOAIImage self, number x, number y, number color)",
returns = "nil"
},
setRGBA = {
type = "method",
description = "Sets a color using RGBA floating point values.\n\n–> MOAIImage self\n–> number x\n–> number y\n–> number r\n–> number g\n–> number b\n[–> number a: Default value is 1.]\n<– nil",
args = "(MOAIImage self, number x, number y, number r, number g, number b, [number a])",
returns = "nil"
},
writePNG = {
type = "method",
description = "Write image to a PNG file.\n\n–> MOAIImage self\n–> string filename\n<– nil",
args = "(MOAIImage self, string filename)",
returns = "nil"
}
}
},
MOAIImageTexture = {
type = "class",
inherits = "MOAITextureBase MOAIImage",
description = "Binds an image (CPU memory) to a texture (GPU memory). Regions of the texture (or the entire texture) may be invalidated. Invalidated regions will be reloaded into GPU memory the next time the texture is bound.",
childs = {
invalidate = {
type = "method",
description = "Invalidate either a sub-region of the texture or the whole texture. Invalidated regions will be reloaded from the image the next time the texture is bound.\n\n–> MOAIImageTexture self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIImageTexture self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
}
}
},
MOAIIndexBuffer = {
type = "class",
inherits = "MOAILuaObject MOAIGfxResource",
description = "Index buffer class. Unused at this time.",
childs = {
release = {
type = "method",
description = "Release any memory held by this index buffer.\n\n–> MOAIIndexBuffer self\n<– nil",
args = "MOAIIndexBuffer self",
returns = "nil"
},
reserve = {
type = "method",
description = "Set capacity of buffer.\n\n–> MOAIIndexBuffer self\n–> number nIndices\n<– nil",
args = "(MOAIIndexBuffer self, number nIndices)",
returns = "nil"
},
setIndex = {
type = "method",
description = "Initialize an index.\n\n–> MOAIIndexBuffer self\n–> number idx\n–> number value\n<– nil",
args = "(MOAIIndexBuffer self, number idx, number value)",
returns = "nil"
}
}
},
MOAIInputDevice = {
type = "class",
inherits = "MOAILuaObject",
description = "Manager class for input bindings. Has no public methods.",
childs = {}
},
MOAIInputMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "Input device class. Has no public methods.",
childs = {}
},
MOAIInstanceEventSource = {
type = "class",
inherits = "MOAIEventSource",
description = "Derivation of MOAIEventSource for non-global Lua objects.",
childs = {
getListener = {
type = "method",
description = "Gets the listener callback for a given event ID.\n\n–> MOAIInstanceEventSource self\n–> number eventID: The ID of the event.\n<– function listener: The listener callback.",
args = "(MOAIInstanceEventSource self, number eventID)",
returns = "function listener",
valuetype = "function"
},
setListener = {
type = "method",
description = "Sets a listener callback for a given event ID. It is up to individual classes to declare their event IDs.\n\n–> MOAIInstanceEventSource self\n–> number eventID: The ID of the event.\n[–> function callback: The callback to be called when the object emits the event. Default value is nil.]\n<– nil",
args = "(MOAIInstanceEventSource self, number eventID, [function callback])",
returns = "nil"
}
}
},
MOAIJoystickSensor = {
type = "class",
inherits = "MOAISensor",
description = "Analog and digital joystick sensor.",
childs = {
getVector = {
type = "method",
description = "Returns the joystick vector.\n\n–> MOAIJoystickSensor self\n<– number x\n<– number y",
args = "MOAIJoystickSensor self",
returns = "(number x, number y)",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the joystick vector changes.\n\n–> MOAIJoystickSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIJoystickSensor self, [function callback])",
returns = "nil"
}
}
},
MOAIJsonParser = {
type = "class",
inherits = "MOAILuaObject",
description = "Converts between Lua and JSON.",
childs = {
decode = {
type = "function",
description = "Decode a JSON string into a hierarchy of Lua tables.\n\n–> string input\n<– table result",
args = "string input",
returns = "table result",
valuetype = "table"
},
encode = {
type = "function",
description = "Encode a hierarchy of Lua tables into a JSON string.\n\n–> table input\n[–> number flags]\n<– string result",
args = "(table input, [number flags])",
returns = "string result",
valuetype = "string"
}
}
},
MOAIKeyboardAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for the native keyboard on Android. Compatible with the iOS methods, albeit with JNI interjection.",
childs = {}
},
MOAIKeyboardIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for the native keyboard. This is a first pass of the keyboard functionality and is missing some important features (such as spell check) that will be added in the near future. We also need to trap the keyboard notifications that tell us the position and dimensions of the keyboard.\nThe decision to divorce the keyboard from the text input field was deliberate. We're not ready (and may never be ready) to own a binding to a full set of native UI widgets. In future releases we'll give better was to connect the software keyboard to a MOAITextBox. This will give better integration of editable text fields with Moai. Even though this is more work up front, it means it will be easier in the long run to keep editable text synchronized with everything else in a scene.\nThe other short term limitation we face is complex text layout for languages such as Arabic. Since we aren't displaying native text fields, input is limited to what MOAITextBox can display. Support for complex text layout is something we want to handle down the road, but until then we're going to be limited.\nIf the keyboard (as written) doesn't meet your needs, if should be straightforward to adapt it into a native text field class that does. You'd need to change it from a singleton to a factory/instance type and add some API to position it on the screen, but otherwise most of the callbacks are already handled.",
childs = {
APPEARANCE_ALERT = {
type = "value"
},
APPEARANCE_DEFAULT = {
type = "value"
},
AUTOCAP_ALL = {
type = "value"
},
AUTOCAP_NONE = {
type = "value"
},
AUTOCAP_SENTENCES = {
type = "value"
},
AUTOCAP_WORDS = {
type = "value"
},
EVENT_INPUT = {
type = "value"
},
EVENT_RETURN = {
type = "value"
},
KEYBOARD_ASCII = {
type = "value"
},
KEYBOARD_DECIMAL_PAD = {
type = "value"
},
KEYBOARD_DEFAULT = {
type = "value"
},
KEYBOARD_EMAIL = {
type = "value"
},
KEYBOARD_NUM_PAD = {
type = "value"
},
KEYBOARD_NUMERIC = {
type = "value"
},
KEYBOARD_PHONE_PAD = {
type = "value"
},
KEYBOARD_TWITTER = {
type = "value"
},
KEYBOARD_URL = {
type = "value"
},
RETURN_KEY_DEFAULT = {
type = "value"
},
RETURN_KEY_DONE = {
type = "value"
},
RETURN_KEY_GO = {
type = "value"
},
RETURN_KEY_JOIN = {
type = "value"
},
RETURN_KEY_NEXT = {
type = "value"
},
RETURN_KEY_ROUTE = {
type = "value"
},
RETURN_KEY_SEARCH = {
type = "value"
},
RETURN_KEY_SEND = {
type = "value"
}
}
},
MOAIKeyboardSensor = {
type = "class",
inherits = "MOAISensor",
description = "Hardware keyboard sensor.",
childs = {
keyDown = {
type = "method",
description = "Checks to see if one or more buttons were pressed during the last iteration.\n\nOverload:\n–> MOAIKeyboardSensor self\n–> string keyCodes: Keycode value(s) to be checked against the input table.\n<– boolean... wasPressed\n\nOverload:\n–> MOAIKeyboardSensor self\n–> number keyCode: Keycode value to be checked against the input table.\n<– boolean wasPressed",
args = "(MOAIKeyboardSensor self, (string keyCodes | number keyCode))",
returns = "(boolean... wasPressed | boolean wasPressed)"
},
keyIsDown = {
type = "method",
description = "Checks to see if the button is currently down.\n\nOverload:\n–> MOAIKeyboardSensor self\n–> string keyCodes: Keycode value(s) to be checked against the input table.\n<– boolean... isDown\n\nOverload:\n–> MOAIKeyboardSensor self\n–> number keyCode: Keycode value to be checked against the input table.\n<– boolean isDown",
args = "(MOAIKeyboardSensor self, (string keyCodes | number keyCode))",
returns = "(boolean... isDown | boolean isDown)"
},
keyIsUp = {
type = "method",
description = "Checks to see if the specified key is currently up.\n\nOverload:\n–> MOAIKeyboardSensor self\n–> string keyCodes: Keycode value(s) to be checked against the input table.\n<– boolean... isUp\n\nOverload:\n–> MOAIKeyboardSensor self\n–> number keyCode: Keycode value to be checked against the input table.\n<– boolean isUp",
args = "(MOAIKeyboardSensor self, (string keyCodes | number keyCode))",
returns = "(boolean... isUp | boolean isUp)"
},
keyUp = {
type = "method",
description = "Checks to see if the specified key was released during the last iteration.\n\nOverload:\n–> MOAIKeyboardSensor self\n–> string keyCodes: Keycode value(s) to be checked against the input table.\n<– boolean... wasReleased\n\nOverload:\n–> MOAIKeyboardSensor self\n–> number keyCode: Keycode value to be checked against the input table.\n<– boolean wasReleased",
args = "(MOAIKeyboardSensor self, (string keyCodes | number keyCode))",
returns = "(boolean... wasReleased | boolean wasReleased)"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when a key is pressed.\n\n–> MOAIKeyboardSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIKeyboardSensor self, [function callback])",
returns = "nil"
}
}
},
MOAILayer = {
type = "class",
inherits = "MOAIProp MOAIClearableView",
description = "Scene controls class.",
childs = {
SORT_ISO = {
type = "value"
},
SORT_NONE = {
type = "value"
},
SORT_PRIORITY_ASCENDING = {
type = "value"
},
SORT_PRIORITY_DESCENDING = {
type = "value"
},
SORT_VECTOR_ASCENDING = {
type = "value"
},
SORT_VECTOR_DESCENDING = {
type = "value"
},
SORT_X_ASCENDING = {
type = "value"
},
SORT_X_DESCENDING = {
type = "value"
},
SORT_Y_ASCENDING = {
type = "value"
},
SORT_Y_DESCENDING = {
type = "value"
},
SORT_Z_ASCENDING = {
type = "value"
},
SORT_Z_DESCENDING = {
type = "value"
},
clear = {
type = "method",
description = "Remove all props from the layer's partition.\n\n–> MOAILayer self\n<– nil",
args = "MOAILayer self",
returns = "nil"
},
getFitting = {
type = "method",
description = "Computes a camera fitting for a given world rect along with an optional screen space padding. To do a fitting, compute the world rect based on whatever you are fitting to, use this method to get the fitting, then animate the camera to match.\n\n–> MOAILayer self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n[–> number xPad]\n[–> number yPad]\n<– number x: X center of fitting (use for camera location).\n<– number y: Y center of fitting (use for camera location).\n<– number s: Scale of fitting (use for camera scale).",
args = "(MOAILayer self, number xMin, number yMin, number xMax, number yMax, [number xPad, [number yPad]])",
returns = "(number x, number y, number s)",
valuetype = "number"
},
getPartition = {
type = "method",
description = "Returns the partition (if any) currently attached to this layer.\n\n–> MOAILayer self\n<– MOAIPartition partition",
args = "MOAILayer self",
returns = "MOAIPartition partition",
valuetype = "MOAIPartition"
},
getSortMode = {
type = "method",
description = "Get the sort mode for rendering.\n\n–> MOAILayer self\n<– number sortMode",
args = "MOAILayer self",
returns = "number sortMode",
valuetype = "number"
},
getSortScale = {
type = "method",
description = "Return the scalar applied to axis sorts.\n\n–> MOAILayer self\n<– number x\n<– number y\n<– number priority",
args = "MOAILayer self",
returns = "(number x, number y, number priority)",
valuetype = "number"
},
insertProp = {
type = "method",
description = "Adds a prop to the layer's partition.\n\n–> MOAILayer self\n–> MOAIProp prop\n<– nil",
args = "(MOAILayer self, MOAIProp prop)",
returns = "nil"
},
removeProp = {
type = "method",
description = "Removes a prop from the layer's partition.\n\n–> MOAILayer self\n–> MOAIProp prop\n<– nil",
args = "(MOAILayer self, MOAIProp prop)",
returns = "nil"
},
setBox2DWorld = {
type = "method",
description = "Sets a Box2D world for debug drawing.\n\n–> MOAILayer self\n–> MOAIBox2DWorld world\n<– nil",
args = "(MOAILayer self, MOAIBox2DWorld world)",
returns = "nil"
},
setCamera = {
type = "method",
description = "Sets a camera for the layer. If no camera is supplied, layer will render using the identity matrix as view/proj.\n\nOverload:\n–> MOAILayer self\n[–> MOAICamera camera: Default value is nil.]\n<– nil\n\nOverload:\n–> MOAILayer self\n[–> MOAICamera2D camera: Default value is nil.]\n<– nil",
args = "(MOAILayer self, [MOAICamera camera | MOAICamera2D camera])",
returns = "nil"
},
setCpSpace = {
type = "method",
description = "Sets a Chipmunk space for debug drawing.\n\n–> MOAILayer self\n–> MOAICpSpace space\n<– nil",
args = "(MOAILayer self, MOAICpSpace space)",
returns = "nil"
},
setParallax = {
type = "method",
description = "Sets the parallax scale for this layer. This is simply a scalar applied to the view transform before rendering.\n\n–> MOAILayer self\n[–> number xParallax: Default value is 1.]\n[–> number yParallax: Default value is 1.]\n[–> number zParallax: Default value is 1.]\n<– nil",
args = "(MOAILayer self, [number xParallax, [number yParallax, [number zParallax]]])",
returns = "nil"
},
setPartition = {
type = "method",
description = "Sets a partition for the layer to use. The layer will automatically create a partition when the first prop is added if no partition has been set.\n\n–> MOAILayer self\n–> MOAIPartition partition\n<– nil",
args = "(MOAILayer self, MOAIPartition partition)",
returns = "nil"
},
setPartitionCull2D = {
type = "method",
description = "Enables 2D partition cull (projection of frustum AABB will be used instead of AABB or frustum).\n\n–> MOAILayer self\n–> boolean partitionCull2D: Default value is false.\n<– nil",
args = "(MOAILayer self, boolean partitionCull2D)",
returns = "nil"
},
setSortMode = {
type = "method",
description = "Set the sort mode for rendering.\n\n–> MOAILayer self\n–> number sortMode: One of MOAILayer.SORT_NONE, MOAILayer.SORT_PRIORITY_ASCENDING, MOAILayer.SORT_PRIORITY_DESCENDING, MOAILayer.SORT_X_ASCENDING, MOAILayer.SORT_X_DESCENDING, MOAILayer.SORT_Y_ASCENDING, MOAILayer.SORT_Y_DESCENDING, MOAILayer.SORT_Z_ASCENDING, MOAILayer.SORT_Z_DESCENDING\n<– nil",
args = "(MOAILayer self, number sortMode)",
returns = "nil"
},
setSortScale = {
type = "method",
description = "Set the scalar applied to axis sorts.\n\n–> MOAILayer self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number z: Default value is 0.]\n[–> number priority: Default value is 1.]\n<– nil",
args = "(MOAILayer self, [number x, [number y, [number z, [number priority]]]])",
returns = "nil"
},
setViewport = {
type = "method",
description = "Set the layer's viewport.\n\n–> MOAILayer self\n–> MOAIViewport viewport\n<– nil",
args = "(MOAILayer self, MOAIViewport viewport)",
returns = "nil"
},
showDebugLines = {
type = "method",
description = "Display debug lines for props in this layer.\n\n–> MOAILayer self\n[–> boolean showDebugLines: Default value is 'true'.]\n<– nil",
args = "(MOAILayer self, [boolean showDebugLines])",
returns = "nil"
},
wndToWorld = {
type = "method",
description = "Project a point from window space into world space and return a normal vector representing a ray cast from the point into the world away from the camera (suitable for 3D picking).\n\n–> MOAILayer self\n–> number x\n–> number y\n–> number z\n<– number x\n<– number y\n<– number z\n<– number xn\n<– number yn\n<– number zn",
args = "(MOAILayer self, number x, number y, number z)",
returns = "(number x, number y, number z, number xn, number yn, number zn)",
valuetype = "number"
},
worldToWnd = {
type = "method",
description = "Transform a point from world space to window space.\n\n–> MOAILayer self\n–> number x\n–> number y\n–> number Z\n<– number x\n<– number y\n<– number z",
args = "(MOAILayer self, number x, number y, number Z)",
returns = "(number x, number y, number z)",
valuetype = "number"
}
}
},
MOAILayer2D = {
type = "class",
inherits = "MOAIProp2D",
description = "2D layer.",
childs = {
SORT_NONE = {
type = "value"
},
SORT_PRIORITY_ASCENDING = {
type = "value"
},
SORT_PRIORITY_DESCENDING = {
type = "value"
},
SORT_VECTOR_ASCENDING = {
type = "value"
},
SORT_VECTOR_DESCENDING = {
type = "value"
},
SORT_X_ASCENDING = {
type = "value"
},
SORT_X_DESCENDING = {
type = "value"
},
SORT_Y_ASCENDING = {
type = "value"
},
SORT_Y_DESCENDING = {
type = "value"
},
clear = {
type = "method",
description = "Remove all props from the layer's partition.\n\n–> MOAILayer2D self\n<– nil",
args = "MOAILayer2D self",
returns = "nil"
},
getFitting = {
type = "method",
description = "Computes a camera fitting for a given world rect along with an optional screen space padding. To do a fitting, compute the world rect based on whatever you are fitting to, use this method to get the fitting, then animate the camera to match.\n\n–> MOAILayer2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n[–> number xPad]\n[–> number yPad]\n<– number x: X center of fitting (use for camera location).\n<– number y: Y center of fitting (use for camera location).\n<– number s: Scale of fitting (use for camera scale).",
args = "(MOAILayer2D self, number xMin, number yMin, number xMax, number yMax, [number xPad, [number yPad]])",
returns = "(number x, number y, number s)",
valuetype = "number"
},
getPartition = {
type = "method",
description = "Returns the partition (if any) currently attached to this layer.\n\n–> MOAILayer2D self\n<– MOAIPartition partition",
args = "MOAILayer2D self",
returns = "MOAIPartition partition",
valuetype = "MOAIPartition"
},
getSortMode = {
type = "method",
description = "Get the sort mode for rendering.\n\n–> MOAILayer2D self\n<– number sortMode",
args = "MOAILayer2D self",
returns = "number sortMode",
valuetype = "number"
},
getSortScale = {
type = "method",
description = "Return the scalar applied to axis sorts.\n\n–> MOAILayer2D self\n<– number x\n<– number y\n<– number priority",
args = "MOAILayer2D self",
returns = "(number x, number y, number priority)",
valuetype = "number"
},
insertProp = {
type = "method",
description = "Adds a prop to the layer's partition.\n\n–> MOAILayer2D self\n–> MOAIProp prop\n<– nil",
args = "(MOAILayer2D self, MOAIProp prop)",
returns = "nil"
},
removeProp = {
type = "method",
description = "Removes a prop from the layer's partition.\n\n–> MOAILayer2D self\n–> MOAIProp prop\n<– nil",
args = "(MOAILayer2D self, MOAIProp prop)",
returns = "nil"
},
setBox2DWorld = {
type = "method",
description = "Sets a Box2D world for debug drawing.\n\n–> MOAILayer2D self\n–> MOAIBox2DWorld world\n<– nil",
args = "(MOAILayer2D self, MOAIBox2DWorld world)",
returns = "nil"
},
setCamera = {
type = "method",
description = "Sets a camera for the layer. If no camera is supplied, layer will render using the identity matrix as view/proj.\n\nOverload:\n–> MOAILayer2D self\n[–> MOAICamera2D camera: Default value is nil.]\n<– nil\n\nOverload:\n–> MOAILayer2D self\n[–> MOAICamera camera: Default value is nil.]\n<– nil",
args = "(MOAILayer2D self, [MOAICamera2D camera | MOAICamera camera])",
returns = "nil"
},
setCpSpace = {
type = "method",
description = "Sets a Chipmunk space for debug drawing.\n\n–> MOAILayer2D self\n–> MOAICpSpace space\n<– nil",
args = "(MOAILayer2D self, MOAICpSpace space)",
returns = "nil"
},
setFrameBuffer = {
type = "method",
description = "Attach a frame buffer. Layer will render to frame buffer instead of the main view.\n\n–> MOAILayer2D self\n–> MOAIFrameBufferTexture frameBuffer\n<– nil",
args = "(MOAILayer2D self, MOAIFrameBufferTexture frameBuffer)",
returns = "nil"
},
setParallax = {
type = "method",
description = "Sets the parallax scale for this layer. This is simply a scalar applied to the view transform before rendering.\n\n–> MOAILayer2D self\n–> number xParallax: Default value is 1.\n–> number yParallax: Default value is 1.\n<– nil",
args = "(MOAILayer2D self, number xParallax, number yParallax)",
returns = "nil"
},
setPartition = {
type = "method",
description = "Sets a partition for the layer to use. The layer will automatically create a partition when the first prop is added if no partition has been set.\n\n–> MOAILayer2D self\n–> MOAIPartition partition\n<– nil",
args = "(MOAILayer2D self, MOAIPartition partition)",
returns = "nil"
},
setSortMode = {
type = "method",
description = "Set the sort mode for rendering.\n\n–> MOAILayer2D self\n–> number sortMode: One of MOAILayer2D.SORT_NONE, MOAILayer2D.SORT_PRIORITY_ASCENDING, MOAILayer2D.SORT_PRIORITY_DESCENDING, MOAILayer2D.SORT_X_ASCENDING, MOAILayer2D.SORT_X_DESCENDING, MOAILayer2D.SORT_Y_ASCENDING, MOAILayer2D.SORT_Y_DESCENDING\n<– nil",
args = "(MOAILayer2D self, number sortMode)",
returns = "nil"
},
setSortScale = {
type = "method",
description = "Set the scalar applied to axis sorts.\n\n–> MOAILayer2D self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number priority: Default value is 1.]\n<– nil",
args = "(MOAILayer2D self, [number x, [number y, [number priority]]])",
returns = "nil"
},
setViewport = {
type = "method",
description = "Set the layer's viewport.\n\n–> MOAILayer2D self\n–> MOAIViewport viewport\n<– nil",
args = "(MOAILayer2D self, MOAIViewport viewport)",
returns = "nil"
},
showDebugLines = {
type = "method",
description = "Display debug lines for props in this layer.\n\n–> MOAILayer2D self\n[–> boolean showDebugLines: Default value is 'true'.]\n<– nil",
args = "(MOAILayer2D self, [boolean showDebugLines])",
returns = "nil"
},
wndToWorld = {
type = "method",
description = "Project a point from window space into world space.\n\n–> MOAILayer2D self\n–> number x\n–> number y\n<– number x\n<– number y",
args = "(MOAILayer2D self, number x, number y)",
returns = "(number x, number y)",
valuetype = "number"
},
worldToWnd = {
type = "method",
description = "Transform a point from world space to window space.\n\n–> MOAILayer2D self\n–> number x\n–> number y\n<– number x\n<– number y",
args = "(MOAILayer2D self, number x, number y)",
returns = "(number x, number y)",
valuetype = "number"
}
}
},
MOAILayerBridge = {
type = "class",
inherits = "MOAITransform",
description = "2D transform for connecting transforms across scenes. Useful for HUD overlay items and map pins.",
childs = {
init = {
type = "method",
description = "Initialize the bridge transform (map coordinates in one layer onto another; useful for rendering screen space objects tied to world space coordinates - map pins, for example).\n\n–> MOAILayerBridge self\n–> MOAITransformBase sourceTransform\n–> MOAILayer sourceLayer\n–> MOAILayer destLayer\n<– nil",
args = "(MOAILayerBridge self, MOAITransformBase sourceTransform, MOAILayer sourceLayer, MOAILayer destLayer)",
returns = "nil"
}
}
},
MOAILocationSensor = {
type = "class",
inherits = "MOAISensor",
description = "Location services sensor.",
childs = {
getLocation = {
type = "method",
description = "Returns the current information about the physical location.\n\n–> MOAILocationSensor self\n<– number longitude\n<– number latitude\n<– number haccuracy: The horizontal (long/lat) accuracy.\n<– number altitude\n<– number vaccuracy: The vertical (altitude) accuracy.\n<– number speed",
args = "MOAILocationSensor self",
returns = "(number longitude, number latitude, number haccuracy, number altitude, number vaccuracy, number speed)",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the location changes.\n\n–> MOAILocationSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAILocationSensor self, [function callback])",
returns = "nil"
}
}
},
MOAILogMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "Singleton for managing debug log messages and log level.",
childs = {
LOG_ERROR = {
type = "value"
},
LOG_NONE = {
type = "value"
},
LOG_STATUS = {
type = "value"
},
LOG_WARNING = {
type = "value"
},
closeFile = {
type = "function",
description = "Resets log output to stdout.\n\n<– nil",
args = "()",
returns = "nil"
},
isDebugBuild = {
type = "function",
description = "Returns a boolean value indicating whether Moai has been compiles as a debug build or not.\n\n<– boolean isDebugBuild",
args = "()",
returns = "boolean isDebugBuild",
valuetype = "boolean"
},
log = {
type = "function",
description = "Alias for print.\n\n–> string message\n<– nil",
args = "string message",
returns = "nil"
},
openFile = {
type = "function",
description = "Opens a new file to receive log messages.\n\n–> string filename\n<– nil",
args = "string filename",
returns = "nil"
},
registerLogMessage = {
type = "function",
description = "Register a format string to handle a log message. Register an empty string to hide messages.\n\n–> number messageID\n[–> string formatString: Default value is an empty string.]\n[–> number level: One of MOAILogMgr.LOG_ERROR, MOAILogMgr.LOG_WARNING, MOAILogMgr.LOG_STATUS. Default value is MOAILogMgr.LOG_STATUS.]\n<– nil",
args = "(number messageID, [string formatString, [number level]])",
returns = "nil"
},
setLogLevel = {
type = "function",
description = "Set the logging level.\n\n–> number logLevel: One of MOAILogMgr LOG_NONE, LOG_ERROR, LOG_WARNING, LOG_STATUS\n<– nil",
args = "number logLevel",
returns = "nil"
},
setTypeCheckLuaParams = {
type = "function",
description = "Set or clear type checking of parameters passed to Lua bound Moai API functions.\n\n[–> boolean check: Default value is false.]\n<– nil",
args = "[boolean check]",
returns = "nil"
}
}
},
MOAILuaObject = {
type = "class",
description = "Base class for all of Moai's Lua classes.",
childs = {
getClass = {
type = "method",
description = "",
args = "()",
returns = "()"
},
getClassName = {
type = "method",
description = "Return the class name for the current object.\n\n–> MOAILuaObject self\n<– string",
args = "MOAILuaObject self",
returns = "string",
valuetype = "string"
},
setInterface = {
type = "method",
description = "",
args = "()",
returns = "()"
}
}
},
MOAIMemStream = {
type = "class",
inherits = "MOAIStream",
description = "MOAIMemStream implements an in-memory stream and grows as needed. The memory stream expands on demands by allocating additional 'chunks' or memory. The chunk size may be configured by the user. Note that the chunks are not guaranteed to be contiguous in memory.",
childs = {
close = {
type = "method",
description = "Close the memory stream and release its buffers.\n\n–> MOAIMemStream self\n<– nil",
args = "MOAIMemStream self",
returns = "nil"
},
open = {
type = "method",
description = "Create a memory stream and optionally reserve some memory and set the chunk size by which the stream will grow if additional memory is needed.\n\n–> MOAIMemStream self\n[–> number reserve: Default value is 0.]\n[–> number chunkSize: Default value is MOAIMemStream.DEFAULT_CHUNK_SIZE (2048 bytes).]\n<– boolean success",
args = "(MOAIMemStream self, [number reserve, [number chunkSize]])",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIMesh = {
type = "class",
inherits = "MOAIDeck",
description = "Loads a texture and renders the contents of a vertex buffer. Grid drawing not supported.",
childs = {
GL_LINE_LOOP = {
type = "value"
},
GL_LINE_STRIP = {
type = "value"
},
GL_LINES = {
type = "value"
},
GL_POINTS = {
type = "value"
},
GL_TRIANGLE_FAN = {
type = "value"
},
GL_TRIANGLE_STRIP = {
type = "value"
},
GL_TRIANGLES = {
type = "value"
},
setIndexBuffer = {
type = "method",
description = "Set the index buffer to render.\n\n–> MOAIMesh self\n–> MOAIIndexBuffer indexBuffer\n<– nil",
args = "(MOAIMesh self, MOAIIndexBuffer indexBuffer)",
returns = "nil"
},
setPenWidth = {
type = "method",
description = "Sets the pen with for drawing prims in this vertex buffer. Only valid with prim types GL_LINES, GL_LINE_LOOP, GL_LINE_STRIP.\n\n–> MOAIMesh self\n–> number penWidth\n<– nil",
args = "(MOAIMesh self, number penWidth)",
returns = "nil"
},
setPointSize = {
type = "method",
description = "Sets the point size for drawing prims in this vertex buffer. Only valid with prim types GL_POINTS.\n\n–> MOAIMesh self\n–> number pointSize\n<– nil",
args = "(MOAIMesh self, number pointSize)",
returns = "nil"
},
setPrimType = {
type = "method",
description = "Sets the prim type the buffer represents.\n\n–> MOAIMesh self\n–> number primType: One of MOAIMesh GL_POINTS, GL_LINES, GL_TRIANGLES, GL_LINE_LOOP, GL_LINE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP\n<– nil",
args = "(MOAIMesh self, number primType)",
returns = "nil"
},
setVertexBuffer = {
type = "method",
description = "Set the vertex buffer to render.\n\n–> MOAIMesh self\n–> MOAIVertexBuffer vertexBuffer\n<– nil",
args = "(MOAIMesh self, MOAIVertexBuffer vertexBuffer)",
returns = "nil"
}
}
},
MOAIMobileAppTrackerIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for WebAppTracker interface.",
childs = {}
},
MOAIMotionSensor = {
type = "class",
inherits = "MOAISensor",
description = "Gravity/acceleration sensor.",
childs = {
getLevel = {
type = "method",
description = "Polls the current status of the level sensor.\n\n–> MOAIMotionSensor self\n<– number x\n<– number y\n<– number z",
args = "MOAIMotionSensor self",
returns = "(number x, number y, number z)",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the level changes.\n\n–> MOAIMotionSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIMotionSensor self, [function callback])",
returns = "nil"
}
}
},
MOAIMoviePlayerAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for simple video playback. Exposed to Lua via MOAIMoviePlayer on all mobile platforms.",
childs = {
init = {
type = "function",
description = "Initialize the video player with the URL of a video to play.\n\n–> string url: The URL of the video to play.\n<– nil",
args = "string url",
returns = "nil"
},
pause = {
type = "function",
description = "Pause video playback.\n\n<– nil",
args = "()",
returns = "nil"
},
play = {
type = "function",
description = "Play the video as soon as playback is ready.\n\n<– nil",
args = "()",
returns = "nil"
},
stop = {
type = "function",
description = "Stop video playback and reset the video player.\n\n<– nil",
args = "()",
returns = "nil"
}
}
},
MOAIMoviePlayerIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for simple video playback. Exposed to Lua via MOAIMoviePlayer on all mobile platforms.",
childs = {}
},
MOAIMultiTexture = {
type = "class",
inherits = "MOAILuaObject MOAIGfxState",
description = "Array of textures for multi-texturing.",
childs = {
reserve = {
type = "method",
description = "Reserve or clears indices for textures.\n\n–> MOAIMultiTexture self\n[–> number total: Default value is 0.]\n<– nil",
args = "(MOAIMultiTexture self, [number total])",
returns = "nil"
},
setTexture = {
type = "method",
description = "Sets of clears a texture for the given index.\n\n–> MOAIMultiTexture self\n–> number index\n[–> MOAITextureBase texture: Default value is nil.]\n<– nil",
args = "(MOAIMultiTexture self, number index, [MOAITextureBase texture])",
returns = "nil"
}
}
},
MOAINode = {
type = "class",
inherits = "MOAIInstanceEventSource",
description = "Base for all attribute bearing Moai objects and dependency graph nodes.",
childs = {
clearAttrLink = {
type = "method",
description = "Clears an attribute *pull* link - call this from the node receiving the attribute value.\n\n–> MOAINode self\n–> number attrID\n<– nil",
args = "(MOAINode self, number attrID)",
returns = "nil"
},
clearNodeLink = {
type = "method",
description = "Clears a dependency on a foreign node.\n\n–> MOAINode self\n–> MOAINode sourceNode\n<– nil",
args = "(MOAINode self, MOAINode sourceNode)",
returns = "nil"
},
forceUpdate = {
type = "method",
description = "Evaluates the dependency graph for this node. Typically, the entire active dependency graph is evaluated once per frame, but in some cases it may be desirable to force evaluation of a node to make sure source dependencies are propagated to it immediately.\n\n–> MOAINode self\n<– nil",
args = "MOAINode self",
returns = "nil"
},
getAttr = {
type = "method",
description = "Returns the value of the attribute if it exists or nil if it doesn't.\n\n–> MOAINode self\n–> number attrID\n<– number value",
args = "(MOAINode self, number attrID)",
returns = "number value",
valuetype = "number"
},
getAttrLink = {
type = "method",
description = "Returns the link if it exists or nil if it doesn't.\n\n–> MOAINode self\n–> number attrID\n<– MOAINode sourceNode\n<– number sourceAttrID",
args = "(MOAINode self, number attrID)",
returns = "(MOAINode sourceNode, number sourceAttrID)",
valuetype = "MOAINode"
},
moveAttr = {
type = "method",
description = "Animate the attribute by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAINode self\n–> number attrID: ID of the attribute to animate.\n–> number delta: Total change to be added to attribute.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAINode self, number attrID, number delta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
scheduleUpdate = {
type = "method",
description = "Schedule the node for an update next time the dependency graph is processed. Any dependent nodes will also be updated.\n\n–> MOAINode self\n<– nil",
args = "MOAINode self",
returns = "nil"
},
seekAttr = {
type = "method",
description = "Animate the attribute by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAINode self\n–> number attrID: ID of the attribute to animate.\n–> number goal: Desired resulting value for attribute.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAINode self, number attrID, number goal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
setAttr = {
type = "method",
description = "Sets the value of an attribute.\n\n–> MOAINode self\n–> number attrID\n–> number value\n<– nil",
args = "(MOAINode self, number attrID, number value)",
returns = "nil"
},
setAttrLink = {
type = "method",
description = "Sets a *pull* attribute connecting an attribute in the node to an attribute in a foreign node.\n\n–> MOAINode self\n–> number attrID: ID of attribute to become dependent of foreign node.\n–> MOAINode sourceNode: Foreign node.\n[–> number sourceAttrID: Attribute in foreign node to control value of attribue. Default value is attrID.]\n<– nil",
args = "(MOAINode self, number attrID, MOAINode sourceNode, [number sourceAttrID])",
returns = "nil"
},
setNodeLink = {
type = "method",
description = "Creates a dependency between the node and a foreign node without the use of attributes; if the foreign node is updated, the dependent node will be updated after.\n\n–> MOAINode self\n–> MOAINode sourceNode\n<– nil",
args = "(MOAINode self, MOAINode sourceNode)",
returns = "nil"
}
}
},
MOAINotificationsAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for push notification integration on Android devices. Exposed to Lua via MOAINotifications on all mobile platforms.",
childs = {
LOCAL_NOTIFICATION_MESSAGE_RECEIVED = {
type = "value",
description = "Event code for a local notification message receipt."
},
REMOTE_NOTIFICATION_ALERT = {
type = "value",
description = "Notification type alerts. Unused."
},
REMOTE_NOTIFICATION_BADGE = {
type = "value",
description = "Notification type icon badges. Unused."
},
REMOTE_NOTIFICATION_MESSAGE_RECEIVED = {
type = "value",
description = "Event code for a push notification message receipt."
},
REMOTE_NOTIFICATION_NONE = {
type = "value",
description = "Notification type none. Unused."
},
REMOTE_NOTIFICATION_REGISTRATION_COMPLETE = {
type = "value",
description = "Event code for notification registration completion."
},
REMOTE_NOTIFICATION_RESULT_ERROR = {
type = "value",
description = "Error code for a failed notification registration or deregistration."
},
REMOTE_NOTIFICATION_RESULT_REGISTERED = {
type = "value",
description = "Error code for a successful notification registration."
},
REMOTE_NOTIFICATION_RESULT_UNREGISTERED = {
type = "value",
description = "Error code for a successful notification deregistration."
},
REMOTE_NOTIFICATION_SOUND = {
type = "value",
description = "Notification type sound. Unused."
},
getAppIconBadgeNumber = {
type = "function",
description = "Get the current icon badge number. Always returns zero.\n\n<– number count",
args = "()",
returns = "number count",
valuetype = "number"
},
localNotificationInSeconds = {
type = "function",
description = "Schedules a local notification to show a number of seconds after calling.\n\n–> string message\n–> number seconds\n<– nil",
args = "(string message, number seconds)",
returns = "nil"
},
registerForRemoteNotifications = {
type = "function",
description = "Register to receive remote notifications.\n\n–> string sender: The identity of the entity that will send remote notifications. See Google documentation.\n<– nil",
args = "string sender",
returns = "nil"
},
setAppIconBadgeNumber = {
type = "function",
description = "Get the current icon badge number. Does nothing.\n\n<– nil",
args = "()",
returns = "nil"
},
unregisterForRemoteNotifications = {
type = "function",
description = "Unregister for remote notifications.\n\n<– nil",
args = "()",
returns = "nil"
}
}
},
MOAINotificationsIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for push notification integration on iOS devices. Exposed to Lua via MOAINotifications on all mobile platforms.",
childs = {
REMOTE_NOTIFICATION_ALERT = {
type = "value",
description = "Notification type alerts."
},
REMOTE_NOTIFICATION_BADGE = {
type = "value",
description = "Notification type icon badges."
},
REMOTE_NOTIFICATION_MESSAGE_RECEIVED = {
type = "value",
description = "Event code for a push notification message receipt."
},
REMOTE_NOTIFICATION_NONE = {
type = "value",
description = "Notification type none."
},
REMOTE_NOTIFICATION_REGISTRATION_COMPLETE = {
type = "value",
description = "Event code for notification registration completion."
},
REMOTE_NOTIFICATION_RESULT_ERROR = {
type = "value",
description = "Error code for a failed notification registration or deregistration."
},
REMOTE_NOTIFICATION_RESULT_REGISTERED = {
type = "value",
description = "Error code for a successful notification registration."
},
REMOTE_NOTIFICATION_RESULT_UNREGISTERED = {
type = "value",
description = "Error code for a successful notification deregistration."
},
REMOTE_NOTIFICATION_SOUND = {
type = "value",
description = "Notification type sound."
}
}
},
MOAIParser = {
type = "class",
inherits = "MOAILuaObject",
description = "Parses strings using a LALR parser. Generates an abstract syntax tree that may then be traversed in Lua. To use, load a CGT file generated by GOLD Parser Builder. Thanks to Devin Cook: http://www.devincook.com/goldparser",
childs = {
loadFile = {
type = "method",
description = "Parses the contents of a file and builds an abstract syntax tree.\n\n–> MOAIParser self\n–> string filename\n<– table ast",
args = "(MOAIParser self, string filename)",
returns = "table ast",
valuetype = "table"
},
loadRules = {
type = "method",
description = "Parses the contents of the specified CGT.\n\n–> MOAIParser self\n–> string filename: The path of the file to read the CGT data from.\n<– nil",
args = "(MOAIParser self, string filename)",
returns = "nil"
},
loadString = {
type = "method",
description = "Parses the contents of a string and builds an abstract syntax tree.\n\n–> MOAIParser self\n–> string filename\n<– table ast",
args = "(MOAIParser self, string filename)",
returns = "table ast",
valuetype = "table"
},
setCallbacks = {
type = "method",
description = "Set Lua syntax tree node handlers for tree traversal.\n\n–> MOAIParser self\n[–> function onStartNonterminal: Default value is nil.]\n[–> function onEndNonterminal: Default value is nil.]\n[–> function onTerminal: Default value is nil.]\n<– nil",
args = "(MOAIParser self, [function onStartNonterminal, [function onEndNonterminal, [function onTerminal]]])",
returns = "nil"
},
traverse = {
type = "method",
description = "Top-down traversal of the abstract syntax tree.\n\n–> MOAIParser self\n<– nil",
args = "MOAIParser self",
returns = "nil"
}
}
},
MOAIParticleCallbackPlugin = {
type = "class",
inherits = "MOAIParticlePlugin",
description = "Allows custom particle processing via C language callbacks.",
childs = {}
},
MOAIParticleDistanceEmitter = {
type = "class",
inherits = "MOAIParticleEmitter",
description = "Particle emitter.",
childs = {
reset = {
type = "method",
description = "Resets the distance traveled. Use this to avoid large emissions when 'warping' the emitter to a new location.\n\n–> MOAIParticleDistanceEmitter self\n<– nil",
args = "MOAIParticleDistanceEmitter self",
returns = "nil"
},
setDistance = {
type = "method",
description = "Set the travel distance required for new particle emission.\n\n–> MOAIParticleDistanceEmitter self\n–> number min: Minimum distance.\n[–> number max: Maximum distance. Default value is min.]\n<– nil",
args = "(MOAIParticleDistanceEmitter self, number min, [number max])",
returns = "nil"
}
}
},
MOAIParticleEmitter = {
type = "class",
inherits = "MOAITransform MOAIAction",
description = "Particle emitter.",
childs = {
setAngle = {
type = "method",
description = "Set the size and angle of the emitter.\n\n–> MOAIParticleEmitter self\n–> number min: Minimum angle in degrees.\n–> number max: Maximum angle in degrees.\n<– nil",
args = "(MOAIParticleEmitter self, number min, number max)",
returns = "nil"
},
setEmission = {
type = "method",
description = "Set the size of each emission.\n\n–> MOAIParticleEmitter self\n–> number min: Minimum emission size.\n[–> number max: Maximum emission size. Defaults to min.]\n<– nil",
args = "(MOAIParticleEmitter self, number min, [number max])",
returns = "nil"
},
setMagnitude = {
type = "method",
description = "Set the starting magnitude of particles deltas.\n\n–> MOAIParticleEmitter self\n–> number min: Minimum magnitude.\n[–> number max: Maximum magnitude. Defaults to min.]\n<– nil",
args = "(MOAIParticleEmitter self, number min, [number max])",
returns = "nil"
},
setRadius = {
type = "method",
description = "Set the shape and radius of the emitter.\n\nOverload:\n–> MOAIParticleEmitter self\n–> number radius\n<– nil\n\nOverload:\n–> MOAIParticleEmitter self\n–> number innerRadius\n–> number outerRadius\n<– nil",
args = "(MOAIParticleEmitter self, (number radius | (number innerRadius, number outerRadius)))",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the shape and dimensions of the emitter.\n\n–> MOAIParticleEmitter self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIParticleEmitter self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setSystem = {
type = "method",
description = "Attaches the emitter to a particle system.\n\n–> MOAIParticleEmitter self\n–> MOAIParticleSystem system\n<– nil",
args = "(MOAIParticleEmitter self, MOAIParticleSystem system)",
returns = "nil"
},
surge = {
type = "method",
description = "Forces the emission of one or more particles.\n\n–> MOAIParticleEmitter self\n[–> number total: Size of surge. Default value is a random emission value for emitter.]\n<– nil",
args = "(MOAIParticleEmitter self, [number total])",
returns = "nil"
}
}
},
MOAIParticleForce = {
type = "class",
inherits = "MOAITransform",
description = "Particle force.",
childs = {
FORCE = {
type = "value"
},
GRAVITY = {
type = "value"
},
OFFSET = {
type = "value"
},
initAttractor = {
type = "method",
description = "Greater force is exerted on particles as they approach attractor.\n\n–> MOAIParticleForce self\n–> number radius: Size of the attractor.\n[–> number magnitude: Strength of the attractor.]\n<– nil",
args = "(MOAIParticleForce self, number radius, [number magnitude])",
returns = "nil"
},
initBasin = {
type = "method",
description = "Greater force is exerted on particles as they leave attractor.\n\n–> MOAIParticleForce self\n–> number radius: Size of the attractor.\n[–> number magnitude: Strength of the attractor.]\n<– nil",
args = "(MOAIParticleForce self, number radius, [number magnitude])",
returns = "nil"
},
initLinear = {
type = "method",
description = "A constant linear force will be applied to the particles.\n\n–> MOAIParticleForce self\n–> number x\n[–> number y]\n<– nil",
args = "(MOAIParticleForce self, number x, [number y])",
returns = "nil"
},
initRadial = {
type = "method",
description = "A constant radial force will be applied to the particles.\n\n–> MOAIParticleForce self\n–> number magnitude\n<– nil",
args = "(MOAIParticleForce self, number magnitude)",
returns = "nil"
},
setType = {
type = "method",
description = "Set the type of force. FORCE will factor in the particle's mass. GRAVITY will ignore the particle's mass. OFFSET will ignore both mass and damping.\n\n–> MOAIParticleForce self\n–> number type: One of MOAIParticleForce.FORCE, MOAIParticleForce.GRAVITY, MOAIParticleForce.OFFSET\n<– nil",
args = "(MOAIParticleForce self, number type)",
returns = "nil"
}
}
},
MOAIParticlePexPlugin = {
type = "class",
inherits = "MOAIParticlePlugin",
description = "Allows custom particle processing derived from .pex file via C language callback.",
childs = {
getTextureName = {
type = "method",
description = "Return the texture name associated with plugin.\n\n–> MOAIParticlePexPlugin self\n<– string textureName",
args = "MOAIParticlePexPlugin self",
returns = "string textureName",
valuetype = "string"
},
load = {
type = "function",
description = "Create a particle plugin from an XML file\n\n–> string fileName: file to load\n<– MOAIParticlePexPlugin plugin: The plugin object that has been initialized with XML's data",
args = "string fileName",
returns = "MOAIParticlePexPlugin plugin",
valuetype = "MOAIParticlePexPlugin"
}
}
},
MOAIParticlePlugin = {
type = "class",
inherits = "MOAILuaObject",
description = "Allows custom particle processing.",
childs = {
getSize = {
type = "method",
description = "Return the particle size expected by the plugin.\n\n–> MOAIParticlePlugin self\n<– number size",
args = "MOAIParticlePlugin self",
returns = "number size",
valuetype = "number"
}
}
},
MOAIParticleScript = {
type = "class",
inherits = "MOAILuaObject",
description = "Particle script.",
childs = {
PARTICLE_DX = {
type = "value"
},
PARTICLE_DY = {
type = "value"
},
PARTICLE_X = {
type = "value"
},
PARTICLE_Y = {
type = "value"
},
SPRITE_BLUE = {
type = "value"
},
SPRITE_GLOW = {
type = "value"
},
SPRITE_GREEN = {
type = "value"
},
SPRITE_IDX = {
type = "value"
},
SPRITE_OPACITY = {
type = "value"
},
SPRITE_RED = {
type = "value"
},
SPRITE_ROT = {
type = "value"
},
SPRITE_X_LOC = {
type = "value"
},
SPRITE_X_SCL = {
type = "value"
},
SPRITE_Y_LOC = {
type = "value"
},
SPRITE_Y_SCL = {
type = "value"
},
add = {
type = "method",
description = "r0 = v0 + v1\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
angleVec = {
type = "method",
description = "Load two registers with the X and Y components of a unit vector with a given angle.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result X.\n–> number r1: Register to store result Y.\n–> number v0: Angle of vector (in degrees).\n<– nil",
args = "(MOAIParticleScript self, number r0, number r1, number v0)",
returns = "nil"
},
cos = {
type = "method",
description = "r0 = cos(v0)\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0)",
returns = "nil"
},
cycle = {
type = "method",
description = "Cycle v0 between v1 and v2.\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n–> number v2\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1, number v2)",
returns = "nil"
},
div = {
type = "method",
description = "r0 = v0 / v1\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
ease = {
type = "method",
description = "Load a register with a value interpolated between two numbers using an ease curve.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result.\n–> number v0: Starting value of the ease.\n–> number v1: Ending value of the ease.\n–> number easeType: See MOAIEaseType for a list of ease types.\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1, number easeType)",
returns = "nil"
},
easeDelta = {
type = "method",
description = "Load a register with a value interpolated between two numbers using an ease curve. Apply as a delta.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result.\n–> number v0: Starting value of the ease.\n–> number v1: Ending value of the ease.\n–> number easeType: See MOAIEaseType for a list of ease types.\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1, number easeType)",
returns = "nil"
},
mul = {
type = "method",
description = "r0 = v0 * v1\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
norm = {
type = "method",
description = "r0 = v0 / |v|\nr1 = v1 / |v|\nWhere |v| == sqrt( v0^2 + v1^2)\n\n–> MOAIParticleScript self\n–> number r0\n–> number r1\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number r1, number v0, number v1)",
returns = "nil"
},
packConst = {
type = "function",
description = "Pack a const value into a particle script param.\n\n–> number const: Const value to pack.\n<– number packed: The packed value.",
args = "number const",
returns = "number packed",
valuetype = "number"
},
packReg = {
type = "function",
description = "Pack a register index into a particle script param.\n\n–> number regIdx: Register index to pack.\n<– number packed: The packed value.",
args = "number regIdx",
returns = "number packed",
valuetype = "number"
},
rand = {
type = "method",
description = "Load a register with a random number from a range.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result.\n–> number v0: Range minimum.\n–> number v1: Range maximum.\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
randVec = {
type = "method",
description = "Load two registers with the X and Y components of a vector with randomly chosen direction and length.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result X.\n–> number r1: Register to store result Y.\n–> number v0: Minimum length of vector.\n–> number v1: Maximum length of vector.\n<– nil",
args = "(MOAIParticleScript self, number r0, number r1, number v0, number v1)",
returns = "nil"
},
set = {
type = "method",
description = "Load a value into a register.\n\n–> MOAIParticleScript self\n–> number r0: Register to store result.\n–> number v0: Value to load.\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0)",
returns = "nil"
},
sin = {
type = "method",
description = "r0 = sin(v0)\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0)",
returns = "nil"
},
sprite = {
type = "method",
description = "Push a new sprite for rendering. To render a particle, first call 'sprite' to create a new sprite at the particle's location. Then modify the sprite's registers to create animated effects based on the age of the particle (normalized to its term).\n\n–> MOAIParticleScript self\n<– nil",
args = "MOAIParticleScript self",
returns = "nil"
},
sub = {
type = "method",
description = "r0 = v0 - v1\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
tan = {
type = "method",
description = "r0 = tan(v0)\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0)",
returns = "nil"
},
time = {
type = "method",
description = "Load the normalized age of the particle into a register.\n\n–> MOAIParticleScript self\n–> number r0\n<– nil",
args = "(MOAIParticleScript self, number r0)",
returns = "nil"
},
vecAngle = {
type = "method",
description = "Compute angle (in degrees) between v0 and v1.\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1)",
returns = "nil"
},
wrap = {
type = "method",
description = "Wrap v0 between v1 and v2.\n\n–> MOAIParticleScript self\n–> number r0\n–> number v0\n–> number v1\n–> number v2\n<– nil",
args = "(MOAIParticleScript self, number r0, number v0, number v1, number v2)",
returns = "nil"
}
}
},
MOAIParticleState = {
type = "class",
inherits = "MOAILuaObject",
description = "Particle state.",
childs = {
clearForces = {
type = "method",
description = "Removes all particle forces from the state.\n\n–> MOAIParticleState self\n<– nil",
args = "MOAIParticleState self",
returns = "nil"
},
pushForce = {
type = "method",
description = "Adds a force to the state.\n\n–> MOAIParticleState self\n–> MOAIParticleForce force\n<– nil",
args = "(MOAIParticleState self, MOAIParticleForce force)",
returns = "nil"
},
setDamping = {
type = "method",
description = "Sets damping for particle physics model.\n\n–> MOAIParticleState self\n–> number damping\n<– nil",
args = "(MOAIParticleState self, number damping)",
returns = "nil"
},
setInitScript = {
type = "method",
description = "Sets the particle script to use for initializing new particles.\n\n–> MOAIParticleState self\n[–> MOAIParticleScript script]\n<– nil",
args = "(MOAIParticleState self, [MOAIParticleScript script])",
returns = "nil"
},
setMass = {
type = "method",
description = "Sets range of masses (chosen randomly) for particles initialized by the state.\n\n–> MOAIParticleState self\n–> number minMass\n[–> number maxMass: Default value is minMass.]\n<– nil",
args = "(MOAIParticleState self, number minMass, [number maxMass])",
returns = "nil"
},
setNext = {
type = "method",
description = "Sets the next state (if any).\n\n–> MOAIParticleState self\n[–> MOAIParticleState next: Default value is nil.]\n<– nil",
args = "(MOAIParticleState self, [MOAIParticleState next])",
returns = "nil"
},
setPlugin = {
type = "method",
description = "Sets the particle plugin to use for initializing and updating particles.\n\n–> MOAIParticleState self\n[–> MOAIParticlePlugin plugin]\n<– nil",
args = "(MOAIParticleState self, [MOAIParticlePlugin plugin])",
returns = "nil"
},
setRenderScript = {
type = "method",
description = "Sets the particle script to use for rendering particles.\n\n–> MOAIParticleState self\n[–> MOAIParticleScript script]\n<– nil",
args = "(MOAIParticleState self, [MOAIParticleScript script])",
returns = "nil"
},
setTerm = {
type = "method",
description = "Sets range of terms (chosen randomly) for particles initialized by the state.\n\n–> MOAIParticleState self\n–> number minTerm\n[–> number maxTerm: Default value is minTerm.]\n<– nil",
args = "(MOAIParticleState self, number minTerm, [number maxTerm])",
returns = "nil"
}
}
},
MOAIParticleSystem = {
type = "class",
inherits = "MOAIProp MOAIAction",
description = "Particle system.",
childs = {
capParticles = {
type = "method",
description = "Controls capping vs. wrapping of particles in overflow situation. Capping will prevent emission of additional particles when system is full. Wrapping will overwrite the oldest particles with new particles.\n\n–> MOAIParticleSystem self\n[–> boolean cap: Default value is true.]\n<– nil",
args = "(MOAIParticleSystem self, [boolean cap])",
returns = "nil"
},
capSprites = {
type = "method",
description = "Controls capping vs. wrapping of sprites.\n\n–> MOAIParticleSystem self\n[–> boolean cap: Default value is true.]\n<– nil",
args = "(MOAIParticleSystem self, [boolean cap])",
returns = "nil"
},
clearSprites = {
type = "method",
description = "Flushes any existing sprites in system.\n\n–> MOAIParticleSystem self\n<– nil",
args = "MOAIParticleSystem self",
returns = "nil"
},
getState = {
type = "method",
description = "Returns a particle state for an index or nil if none exists.\n\n–> MOAIParticleSystem self\n–> number index\n<– MOAIParticleState state",
args = "(MOAIParticleSystem self, number index)",
returns = "MOAIParticleState state",
valuetype = "MOAIParticleState"
},
isIdle = {
type = "method",
description = "Returns true if the current system is not currently processing any particles.\n\n–> MOAIParticleSystem self\n<– boolean isIdle: Indicates whether the system is currently idle.",
args = "MOAIParticleSystem self",
returns = "boolean isIdle",
valuetype = "boolean"
},
pushParticle = {
type = "method",
description = "Adds a particle to the system.\n\n–> MOAIParticleSystem self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number dx: Default value is 0.]\n[–> number dy: Default value is 0.]\n<– boolean result: true if particle was added, false if not.",
args = "(MOAIParticleSystem self, [number x, [number y, [number dx, [number dy]]]])",
returns = "boolean result",
valuetype = "boolean"
},
pushSprite = {
type = "method",
description = "Adds a sprite to the system. Sprite will persist until particle simulation is begun or 'clearSprites' is called.\n\n–> MOAIParticleSystem self\n–> number x\n–> number y\n[–> number rot: Rotation in degrees. Default value is 0.]\n[–> number xScale: Default value is 1.]\n[–> number yScale: Default value is 1.]\n<– boolean result: true is sprite was added, false if not.",
args = "(MOAIParticleSystem self, number x, number y, [number rot, [number xScale, [number yScale]]])",
returns = "boolean result",
valuetype = "boolean"
},
reserveParticles = {
type = "method",
description = "Reserve particle capacity of system.\n\n–> MOAIParticleSystem self\n–> number nParticles: Total number of particle records.\n–> number particleSize: Number of parameters reserved for the particle.\n<– nil",
args = "(MOAIParticleSystem self, number nParticles, number particleSize)",
returns = "nil"
},
reserveSprites = {
type = "method",
description = "Reserve sprite capacity of system.\n\n–> MOAIParticleSystem self\n–> number nSprites\n<– nil",
args = "(MOAIParticleSystem self, number nSprites)",
returns = "nil"
},
reserveStates = {
type = "method",
description = "Reserve total number of states for system.\n\n–> MOAIParticleSystem self\n–> number nStates\n<– nil",
args = "(MOAIParticleSystem self, number nStates)",
returns = "nil"
},
setComputeBounds = {
type = "method",
description = "Set the a flag controlling whether the particle system re-computes its bounds every frame.\n\n–> MOAIParticleSystem self\n[–> boolean computBounds: Default value is false.]\n<– nil",
args = "(MOAIParticleSystem self, [boolean computBounds])",
returns = "nil"
},
setSpriteColor = {
type = "method",
description = "Set the color of the most recently added sprite.\n\n–> MOAIParticleSystem self\n–> number r\n–> number g\n–> number b\n–> number a\n<– nil",
args = "(MOAIParticleSystem self, number r, number g, number b, number a)",
returns = "nil"
},
setSpriteDeckIdx = {
type = "method",
description = "Set the sprite's deck index.\n\n–> MOAIParticleSystem self\n–> number index\n<– nil",
args = "(MOAIParticleSystem self, number index)",
returns = "nil"
},
setState = {
type = "method",
description = "Set a particle state.\n\n–> MOAIParticleSystem self\n–> number index\n–> MOAIParticleState state\n<– nil",
args = "(MOAIParticleSystem self, number index, MOAIParticleState state)",
returns = "nil"
},
surge = {
type = "method",
description = "Release a batch emission or particles into the system.\n\n–> MOAIParticleSystem self\n[–> number total: Default value is 1.]\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number dx: Default value is 0.]\n[–> number dy: Default value is 0.]\n<– nil",
args = "(MOAIParticleSystem self, [number total, [number x, [number y, [number dx, [number dy]]]]])",
returns = "nil"
}
}
},
MOAIParticleTimedEmitter = {
type = "class",
inherits = "MOAIParticleEmitter",
description = "Particle emitter.",
childs = {
setFrequency = {
type = "method",
description = "Set timer frequency.\n\n–> MOAIParticleTimedEmitter self\n–> number min\n[–> number max: Default value is min.]\n<– nil",
args = "(MOAIParticleTimedEmitter self, number min, [number max])",
returns = "nil"
}
}
},
MOAIPartition = {
type = "class",
inherits = "MOAILuaObject",
description = "Class for optimizing spatial queries against sets of primitives. Configure for performance; default behavior is a simple list.",
childs = {
PLANE_XY = {
type = "value"
},
PLANE_XZ = {
type = "value"
},
PLANE_YZ = {
type = "value"
},
clear = {
type = "method",
description = "Remove all props from the partition.\n\n–> MOAIPartition self\n<– nil",
args = "MOAIPartition self",
returns = "nil"
},
insertProp = {
type = "method",
description = "Inserts a prop into the partition. A prop can only be in one partition at a time.\n\n–> MOAIPartition self\n–> MOAIProp prop\n<– nil",
args = "(MOAIPartition self, MOAIProp prop)",
returns = "nil"
},
propForPoint = {
type = "method",
description = "Returns the prop with the highest priority that contains the given world space point.\n\n–> MOAIPartition self\n–> number x\n–> number y\n–> number z\n[–> number sortMode: One of the MOAILayer sort modes. Default value is SORT_PRIORITY_ASCENDING.]\n[–> number xScale: X scale for vector sort. Default value is 0.]\n[–> number yScale: Y scale for vector sort. Default value is 0.]\n[–> number zScale: Z scale for vector sort. Default value is 0.]\n[–> number priorityScale: Priority scale for vector sort. Default value is 1.]\n<– MOAIProp prop: The prop under the point or nil if no prop found.",
args = "(MOAIPartition self, number x, number y, number z, [number sortMode, [number xScale, [number yScale, [number zScale, [number priorityScale]]]]])",
returns = "MOAIProp prop",
valuetype = "MOAIProp"
},
propForRay = {
type = "method",
description = "Returns the prop closest to the camera that intersects the given ray\n\n–> MOAIPartition self\n–> number x\n–> number y\n–> number z\n–> number xdirection\n–> number ydirection\n–> number zdirection\n<– MOAIProp prop: The prop under the point in order of depth or nil if no prop found.",
args = "(MOAIPartition self, number x, number y, number z, number xdirection, number ydirection, number zdirection)",
returns = "MOAIProp prop",
valuetype = "MOAIProp"
},
propListForPoint = {
type = "method",
description = "Returns all props under a given world space point.\n\n–> MOAIPartition self\n–> number x\n–> number y\n–> number z\n[–> number sortMode: One of the MOAILayer sort modes. Default value is SORT_NONE.]\n[–> number xScale: X scale for vector sort. Default value is 0.]\n[–> number yScale: Y scale for vector sort. Default value is 0.]\n[–> number zScale: Z scale for vector sort. Default value is 0.]\n[–> number priorityScale: Priority scale for vector sort. Default value is 1.]\n<– ... props: The props under the point, all pushed onto the stack.",
args = "(MOAIPartition self, number x, number y, number z, [number sortMode, [number xScale, [number yScale, [number zScale, [number priorityScale]]]]])",
returns = "... props",
valuetype = "..."
},
propListForRay = {
type = "method",
description = "Returns all props under a given world space point.\n\n–> MOAIPartition self\n–> number x\n–> number y\n–> number z\n–> number xdirection\n–> number ydirection\n–> number zdirection\n[–> number sortMode: One of the MOAILayer sort modes. Default value is SORT_KEY_ASCENDING.]\n[–> number xScale: X scale for vector sort. Default value is 0.]\n[–> number yScale: Y scale for vector sort. Default value is 0.]\n[–> number zScale: Z scale for vector sort. Default value is 0.]\n[–> number priorityScale: Priority scale for vector sort. Default value is 1.]\n<– ... props: The props under the point in order of depth, all pushed onto the stack.",
args = "(MOAIPartition self, number x, number y, number z, number xdirection, number ydirection, number zdirection, [number sortMode, [number xScale, [number yScale, [number zScale, [number priorityScale]]]]])",
returns = "... props",
valuetype = "..."
},
propListForRect = {
type = "method",
description = "Returns all props under a given world space rect.\n\n–> MOAIPartition self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n[–> number sortMode: One of the MOAILayer sort modes. Default value is SORT_NONE.]\n[–> number xScale: X scale for vector sort. Default value is 0.]\n[–> number yScale: Y scale for vector sort. Default value is 0.]\n[–> number zScale: Z scale for vector sort. Default value is 0.]\n[–> number priorityScale: Priority scale for vector sort. Default value is 1.]\n<– ... props: The props under the rect, all pushed onto the stack.",
args = "(MOAIPartition self, number xMin, number yMin, number xMax, number yMax, [number sortMode, [number xScale, [number yScale, [number zScale, [number priorityScale]]]]])",
returns = "... props",
valuetype = "..."
},
removeProp = {
type = "method",
description = "Removes a prop from the partition.\n\n–> MOAIPartition self\n–> MOAIProp prop\n<– nil",
args = "(MOAIPartition self, MOAIProp prop)",
returns = "nil"
},
reserveLevels = {
type = "method",
description = "Reserves a stack of levels in the partition. Levels must be initialized with setLevel (). This will trigger a full rebuild of the partition if it contains any props.\n\n–> MOAIPartition self\n–> number nLevels\n<– nil",
args = "(MOAIPartition self, number nLevels)",
returns = "nil"
},
setLevel = {
type = "method",
description = "Initializes a level previously created by reserveLevels (). This will trigger a full rebuild of the partition if it contains any props. Each level is a loose grid. Props of a given size may be placed by the system into any level with cells large enough to accommodate them. The dimensions of a level control how many cells the level contains. If an object goes off of the edge of a level, it will wrap around to the other side. It is possible to model a quad tree by initializing levels correctly, but for some simulations better structures may be possible.\n\n–> MOAIPartition self\n–> number levelID\n–> number cellSize: Dimensions of the layer's cells.\n–> number xCells: Width of layer in cells.\n–> number yCells: Height of layer in cells.\n<– nil",
args = "(MOAIPartition self, number levelID, number cellSize, number xCells, number yCells)",
returns = "nil"
},
setPlane = {
type = "method",
description = "Selects the plane the partition will use. If this is different from the current plane then all non-global props will be redistributed. Redistribution works by moving all props to the 'empties' cell and then scheduling them all for a dep node update (which refreshes the prop's bounds and may also flag it as global).\n\n–> MOAIPartition self\n–> number planeID: One of MOAIPartition::PLANE_XY, MOAIPartition::PLANE_XZ, MOAIPartition::PLANE_YZ. Default value is MOAIPartition::PLANE_XY.\n<– nil",
args = "(MOAIPartition self, number planeID)",
returns = "nil"
}
}
},
MOAIPathFinder = {
type = "class",
inherits = "MOAILuaObject",
description = "Object for maintaining pathfinding state.",
childs = {
findPath = {
type = "method",
description = "Attempts to find an efficient path from the start node to the finish node. May be called incrementally.\n\n–> MOAIPathFinder self\n[–> number iterations]\n<– boolean more",
args = "(MOAIPathFinder self, [number iterations])",
returns = "boolean more",
valuetype = "boolean"
},
getGraph = {
type = "method",
description = "Returns the attached graph (if any).\n\n–> MOAIPathFinder self\n<– MOAIPathGraph graph",
args = "MOAIPathFinder self",
returns = "MOAIPathGraph graph",
valuetype = "MOAIPathGraph"
},
getPathEntry = {
type = "method",
description = "Returns a path entry. This is a node ID that may be passed back to the graph to get a location.\n\n–> MOAIPathFinder self\n–> number index\n<– number entry",
args = "(MOAIPathFinder self, number index)",
returns = "number entry",
valuetype = "number"
},
getPathSize = {
type = "method",
description = "Returns the size of the path (in nodes).\n\n–> MOAIPathFinder self\n<– number size",
args = "MOAIPathFinder self",
returns = "number size",
valuetype = "number"
},
init = {
type = "method",
description = "Specify the ID of the start and target node.\n\n–> MOAIPathFinder self\n–> number startNodeID\n–> number targetNodeID\n<– nil",
args = "(MOAIPathFinder self, number startNodeID, number targetNodeID)",
returns = "nil"
},
reserveTerrainWeights = {
type = "method",
description = "Specify the size of the terrain weight vector.\n\n–> MOAIPathFinder self\n[–> number size: Default value is 0.]\n<– nil",
args = "(MOAIPathFinder self, [number size])",
returns = "nil"
},
setFlags = {
type = "method",
description = "Set flags to use for pathfinding. These are graph specific flags provided by the graph implementation.\n\n–> MOAIPathFinder self\n[–> number heuristic]\n<– nil",
args = "(MOAIPathFinder self, [number heuristic])",
returns = "nil"
},
setGraph = {
type = "method",
description = "Set graph data to use for pathfinding.\n\nOverload:\n–> MOAIPathFinder self\n[–> MOAIGrid grid: Default value is nil.]\n<– nil\n\nOverload:\n–> MOAIPathFinder self\n[–> MOAIGridPathGraph gridPathGraph: Default value is nil.]\n<– nil",
args = "(MOAIPathFinder self, [MOAIGrid grid | MOAIGridPathGraph gridPathGraph])",
returns = "nil"
},
setHeuristic = {
type = "method",
description = "Set heuristic to use for pathfinding. This is a const provided by the graph implementation being used.\n\n–> MOAIPathFinder self\n[–> number heuristic]\n<– nil",
args = "(MOAIPathFinder self, [number heuristic])",
returns = "nil"
},
setTerrainDeck = {
type = "method",
description = "Set terrain deck to use with graph.\n\n–> MOAIPathFinder self\n[–> MOAIPathTerrainDeck terrainDeck: Default value is nil.]\n<– nil",
args = "(MOAIPathFinder self, [MOAIPathTerrainDeck terrainDeck])",
returns = "nil"
},
setTerrainMask = {
type = "method",
description = "Set 32-bit mask to apply to terrain samples.\n\n–> MOAIPathFinder self\n[–> number mask: Default value is 0xffffffff.]\n<– nil",
args = "(MOAIPathFinder self, [number mask])",
returns = "nil"
},
setTerrainWeight = {
type = "method",
description = "Set a component of the terrain weight vector.\n\n–> MOAIPathFinder self\n–> number index\n[–> number deltaScale: Default value is 0.]\n[–> number penaltyScale: Default value is 0.]\n<– nil",
args = "(MOAIPathFinder self, number index, [number deltaScale, [number penaltyScale]])",
returns = "nil"
},
setWeight = {
type = "method",
description = "Sets weights to be applied to G and H.\n\n–> MOAIPathFinder self\n[–> number gWeight: Default value is 1.0.]\n[–> number hWeight: Default value is 1.0.]\n<– nil",
args = "(MOAIPathFinder self, [number gWeight, [number hWeight]])",
returns = "nil"
}
}
},
MOAIPathGraph = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIPathTerrainDeck = {
type = "class",
inherits = "MOAILuaObject",
description = "Terrain specifications for use with pathfinding graphs. Contains indexed terrain types for graph nodes.",
childs = {
getMask = {
type = "method",
description = "Returns mask for cell.\n\n–> MOAIPathTerrainDeck self\n–> number idx\n<– number mask",
args = "(MOAIPathTerrainDeck self, number idx)",
returns = "number mask",
valuetype = "number"
},
getTerrainVec = {
type = "method",
description = "Returns terrain vector for cell.\n\n–> MOAIPathTerrainDeck self\n–> number idx\n<– ...",
args = "(MOAIPathTerrainDeck self, number idx)",
returns = "...",
valuetype = "..."
},
reserve = {
type = "method",
description = "Allocates terrain vectors.\n\n–> MOAIPathTerrainDeck self\n–> number deckSize\n–> number terrainVecSize\n<– nil",
args = "(MOAIPathTerrainDeck self, number deckSize, number terrainVecSize)",
returns = "nil"
},
setMask = {
type = "method",
description = "Returns mask for cell.\n\n–> MOAIPathTerrainDeck self\n–> number idx\n–> number mask\n<– nil",
args = "(MOAIPathTerrainDeck self, number idx, number mask)",
returns = "nil"
},
setTerrainVec = {
type = "method",
description = "Sets terrain vector for cell.\n\n–> MOAIPathTerrainDeck self\n–> number idx\n–> class float : MOAILuaObject... values\n<– nil",
args = "(MOAIPathTerrainDeck self, number idx, class float... values)",
returns = "nil"
}
}
},
MOAIPointerSensor = {
type = "class",
inherits = "MOAISensor",
description = "Pointer sensor.",
childs = {
getLoc = {
type = "method",
description = "Returns the location of the pointer on the screen.\n\n–> MOAIPointerSensor self\n<– number x\n<– number y",
args = "MOAIPointerSensor self",
returns = "(number x, number y)",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the pointer location changes.\n\n–> MOAIPointerSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIPointerSensor self, [function callback])",
returns = "nil"
}
}
},
MOAIProp = {
type = "class",
inherits = "MOAITransform MOAIColor MOAIRenderable",
description = "Base class for props.",
childs = {
ATTR_INDEX = {
type = "value"
},
BLEND_ADD = {
type = "value"
},
BLEND_MULTIPLY = {
type = "value"
},
BLEND_NORMAL = {
type = "value"
},
CULL_ALL = {
type = "value"
},
CULL_BACK = {
type = "value"
},
CULL_FRONT = {
type = "value"
},
CULL_NONE = {
type = "value"
},
DEPTH_TEST_ALWAYS = {
type = "value"
},
DEPTH_TEST_DISABLE = {
type = "value"
},
DEPTH_TEST_EQUAL = {
type = "value"
},
DEPTH_TEST_GREATER = {
type = "value"
},
DEPTH_TEST_GREATER_EQUAL = {
type = "value"
},
DEPTH_TEST_LESS = {
type = "value"
},
DEPTH_TEST_LESS_EQUAL = {
type = "value"
},
DEPTH_TEST_NEVER = {
type = "value"
},
DEPTH_TEST_NOTEQUAL = {
type = "value"
},
FRAME_FROM_DECK = {
type = "value"
},
FRAME_FROM_PARENT = {
type = "value"
},
FRAME_FROM_SELF = {
type = "value"
},
GL_DST_ALPHA = {
type = "value"
},
GL_DST_COLOR = {
type = "value"
},
GL_FUNC_ADD = {
type = "value"
},
GL_FUNC_REVERSE_SUBTRACT = {
type = "value"
},
GL_FUNC_SUBTRACT = {
type = "value"
},
GL_ONE = {
type = "value"
},
GL_ONE_MINUS_DST_ALPHA = {
type = "value"
},
GL_ONE_MINUS_DST_COLOR = {
type = "value"
},
GL_ONE_MINUS_SRC_ALPHA = {
type = "value"
},
GL_ONE_MINUS_SRC_COLOR = {
type = "value"
},
GL_SRC_ALPHA = {
type = "value"
},
GL_SRC_ALPHA_SATURATE = {
type = "value"
},
GL_SRC_COLOR = {
type = "value"
},
GL_ZERO = {
type = "value"
},
getBounds = {
type = "method",
description = "Return the prop's local bounds or 'nil' if prop bounds is global or missing. The bounds are in model space and will be overridden by the prop's bounds if it's been set (using setBounds ())\n\n–> MOAIProp self\n<– number xMin\n<– number yMin\n<– number zMin\n<– number xMax\n<– number yMax\n<– number zMax",
args = "MOAIProp self",
returns = "(number xMin, number yMin, number zMin, number xMax, number yMax, number zMax)",
valuetype = "number"
},
getDims = {
type = "method",
description = "Return the prop's width and height or 'nil' if prop rect is global.\n\n–> MOAIProp self\n<– number width: X max - X min\n<– number height: Y max - Y min\n<– number depth: Z max - Z min",
args = "MOAIProp self",
returns = "(number width, number height, number depth)",
valuetype = "number"
},
getGrid = {
type = "method",
description = "Get the grid currently connected to the prop.\n\n–> MOAIProp self\n<– MOAIGrid grid: Current grid or nil.",
args = "MOAIProp self",
returns = "MOAIGrid grid",
valuetype = "MOAIGrid"
},
getIndex = {
type = "method",
description = "Gets the value of the deck indexer.\n\n–> MOAIProp self\n<– number index",
args = "MOAIProp self",
returns = "number index",
valuetype = "number"
},
getPriority = {
type = "method",
description = "Returns the current priority of the node or 'nil' if the priority is uninitialized.\n\n–> MOAIProp self\n<– number priority: The node's priority or nil.",
args = "MOAIProp self",
returns = "number priority",
valuetype = "number"
},
getWorldBounds = {
type = "method",
description = "Return the prop's world bounds or 'nil' if prop bounds is global or missing.\n\n–> MOAIProp self\n<– number xMin\n<– number yMin\n<– number zMin\n<– number xMax\n<– number yMax\n<– number zMax",
args = "MOAIProp self",
returns = "(number xMin, number yMin, number zMin, number xMax, number yMax, number zMax)",
valuetype = "number"
},
inside = {
type = "method",
description = "Returns true if the given world space point falls inside the prop's bounds.\n\n–> MOAIProp self\n–> number x\n–> number y\n–> number z\n[–> number pad: Pad the hit bounds (in the prop's local space)]\n<– boolean isInside",
args = "(MOAIProp self, number x, number y, number z, [number pad])",
returns = "boolean isInside",
valuetype = "boolean"
},
isVisible = {
type = "method",
description = "Returns true if the given prop is visible.\n\n–> MOAIProp self\n<– boolean isVisible",
args = "MOAIProp self",
returns = "boolean isVisible",
valuetype = "boolean"
},
setBillboard = {
type = "method",
description = "If set, prop will face camera when rendering.\n\n–> MOAIProp self\n[–> boolean billboard: Default value is false.]\n<– nil",
args = "(MOAIProp self, [boolean billboard])",
returns = "nil"
},
setBlendEquation = {
type = "method",
description = "Set the blend equation. This determines how the srcFactor and dstFactor values set with setBlendMode are interpreted.\n\nOverload:\n–> MOAIProp self\n<– nil\n\nOverload:\n–> MOAIProp self\n–> number equation: One of GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT.\n<– nil",
args = "(MOAIProp self, [number equation])",
returns = "nil"
},
setBlendMode = {
type = "method",
description = "Set the blend mode.\n\nOverload:\n–> MOAIProp self\n<– nil\n\nOverload:\n–> MOAIProp self\n–> number mode: One of MOAIProp.BLEND_NORMAL, MOAIProp.BLEND_ADD, MOAIProp.BLEND_MULTIPLY.\n<– nil\n\nOverload:\n–> MOAIProp self\n–> number srcFactor\n–> number dstFactor\n<– nil",
args = "(MOAIProp self, [number mode | (number srcFactor, number dstFactor)])",
returns = "nil"
},
setBounds = {
type = "method",
description = "Sets or clears the partition bounds override.\n\nOverload:\n–> MOAIProp self\n<– nil\n\nOverload:\n–> MOAIProp self\n–> number xMin\n–> number yMin\n–> number zMin\n–> number xMax\n–> number yMax\n–> number zMax\n<– nil",
args = "(MOAIProp self, [number xMin, number yMin, number zMin, number xMax, number yMax, number zMax])",
returns = "nil"
},
setCullMode = {
type = "method",
description = "Sets and enables face culling.\n\n–> MOAIProp self\n[–> number cullMode: Default value is MOAIProp.CULL_NONE.]\n<– nil",
args = "(MOAIProp self, [number cullMode])",
returns = "nil"
},
setDeck = {
type = "method",
description = "Sets or clears the deck to be indexed by the prop.\n\n–> MOAIProp self\n[–> MOAIDeck deck: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAIDeck deck])",
returns = "nil"
},
setDepthMask = {
type = "method",
description = "Disables or enables depth writing.\n\n–> MOAIProp self\n[–> boolean depthMask: Default value is true.]\n<– nil",
args = "(MOAIProp self, [boolean depthMask])",
returns = "nil"
},
setDepthTest = {
type = "method",
description = "Sets and enables depth testing (assuming depth buffer is present).\n\n–> MOAIProp self\n[–> number depthFunc: Default value is MOAIProp.DEPTH_TEST_DISABLE.]\n<– nil",
args = "(MOAIProp self, [number depthFunc])",
returns = "nil"
},
setExpandForSort = {
type = "method",
description = "Used when drawing with a layout scheme (i.e. MOAIGrid). Expanding for sort causes the prop to emit a sub-prim for each component of the layout. For example, when attaching a MOAIGrid to a prop, each cell of the grid will be added to the render queue for sorting against all other props and sub-prims. This is obviously less efficient, but still more efficient then using an separate prop for each cell or object.\n\n–> MOAIProp self\n–> boolean expandForSort: Default value is false.\n<– nil",
args = "(MOAIProp self, boolean expandForSort)",
returns = "nil"
},
setGrid = {
type = "method",
description = "Sets or clears the prop's grid indexer. The grid indexer (if any) will override the standard indexer.\n\n–> MOAIProp self\n[–> MOAIGrid grid: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAIGrid grid])",
returns = "nil"
},
setGridScale = {
type = "method",
description = "Scale applied to deck items before rendering to grid cell.\n\n–> MOAIProp self\n[–> number xScale: Default value is 1.]\n[–> number yScale: Default value is 1.]\n<– nil",
args = "(MOAIProp self, [number xScale, [number yScale]])",
returns = "nil"
},
setIndex = {
type = "method",
description = "Set the prop's index into its deck.\n\n–> MOAIProp self\n[–> number index: Default value is 1.]\n<– nil",
args = "(MOAIProp self, [number index])",
returns = "nil"
},
setParent = {
type = "method",
description = "This method has been deprecated. Use MOAINode setAttrLink instead.\n\n–> MOAIProp self\n[–> MOAINode parent: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAINode parent])",
returns = "nil"
},
setPriority = {
type = "method",
description = "Sets or clears the node's priority. Clear the priority to have MOAIPartition automatically assign a priority to a node when it is added.\n\n–> MOAIProp self\n[–> number priority: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [number priority])",
returns = "nil"
},
setRemapper = {
type = "method",
description = "Set a remapper for this prop to use when drawing deck members.\n\n–> MOAIProp self\n[–> MOAIDeckRemapper remapper: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAIDeckRemapper remapper])",
returns = "nil"
},
setScissorRect = {
type = "method",
description = "Set or clear the prop's scissor rect.\n\n–> MOAIProp self\n[–> MOAIScissorRect scissorRect: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAIScissorRect scissorRect])",
returns = "nil"
},
setShader = {
type = "method",
description = "Sets or clears the prop's shader. The prop's shader takes precedence over any shader specified by the deck or its elements.\n\n–> MOAIProp self\n[–> MOAIShader shader: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAIShader shader])",
returns = "nil"
},
setTexture = {
type = "method",
description = "Set or load a texture for this prop. The prop's texture will override the deck's texture.\n\n–> MOAIProp self\n–> variant texture: A MOAITexture, MOAIMultiTexture, MOAIDataBuffer or a path to a texture file\n[–> number transform: Any bitwise combination of MOAITextureBase.QUANTIZE, MOAITextureBase.TRUECOLOR, MOAITextureBase.PREMULTIPLY_ALPHA]\n<– MOAIGfxState texture",
args = "(MOAIProp self, variant texture, [number transform])",
returns = "MOAIGfxState texture",
valuetype = "MOAIGfxState"
},
setUVTransform = {
type = "method",
description = "Sets or clears the prop's UV transform.\n\n–> MOAIProp self\n[–> MOAITransformBase transform: Default value is nil.]\n<– nil",
args = "(MOAIProp self, [MOAITransformBase transform])",
returns = "nil"
},
setVisible = {
type = "method",
description = "Sets or clears the prop's visibility.\n\n–> MOAIProp self\n[–> boolean visible: Default value is true.]\n<– nil",
args = "(MOAIProp self, [boolean visible])",
returns = "nil"
}
}
},
MOAIProp2D = {
type = "class",
inherits = "MOAITransform2D MOAIColor MOAIRenderable",
description = "2D prop.",
childs = {
getBounds = {
type = "method",
description = "Return the prop's local bounds or 'nil' if prop bounds is global or missing. The bounds are in model space and will be overridden by the prop's frame if it's been set (using setFrame ())\n\n–> MOAIProp2D self\n<– number xMin\n<– number yMin\n<– number xMax\n<– number yMax",
args = "MOAIProp2D self",
returns = "(number xMin, number yMin, number xMax, number yMax)",
valuetype = "number"
},
getGrid = {
type = "method",
description = "Get the grid currently connected to the prop.\n\n–> MOAIProp2D self\n<– MOAIGrid grid: Current grid or nil.",
args = "MOAIProp2D self",
returns = "MOAIGrid grid",
valuetype = "MOAIGrid"
},
getIndex = {
type = "method",
description = "Gets the value of the deck indexer.\n\n–> MOAIProp2D self\n<– number index",
args = "MOAIProp2D self",
returns = "number index",
valuetype = "number"
},
getPriority = {
type = "method",
description = "Returns the current priority of the node or 'nil' if the priority is uninitialized.\n\n–> MOAIProp2D self\n<– number priority: The node's priority or nil.",
args = "MOAIProp2D self",
returns = "number priority",
valuetype = "number"
},
inside = {
type = "method",
description = "Returns true if the given world space point falls inside the prop's bounds.\n\n–> MOAIProp2D self\n–> number x\n–> number y\n–> number z\n[–> number pad: Pad the hit bounds (in the prop's local space)]\n<– boolean isInside",
args = "(MOAIProp2D self, number x, number y, number z, [number pad])",
returns = "boolean isInside",
valuetype = "boolean"
},
setBlendMode = {
type = "method",
description = "Set the blend mode.\n\nOverload:\n–> MOAIProp2D self\n<– nil\n\nOverload:\n–> MOAIProp2D self\n–> number mode: One of MOAIProp2D.BLEND_NORMAL, MOAIProp2D.BLEND_ADD, MOAIProp2D.BLEND_MULTIPLY.\n<– nil\n\nOverload:\n–> MOAIProp2D self\n–> number srcFactor\n–> number dstFactor\n<– nil",
args = "(MOAIProp2D self, [number mode | (number srcFactor, number dstFactor)])",
returns = "nil"
},
setCullMode = {
type = "method",
description = "Sets and enables face culling.\n\n–> MOAIProp2D self\n[–> number cullMode: Default value is MOAIProp2D.CULL_NONE.]\n<– nil",
args = "(MOAIProp2D self, [number cullMode])",
returns = "nil"
},
setDeck = {
type = "method",
description = "Sets or clears the deck to be indexed by the prop.\n\n–> MOAIProp2D self\n[–> MOAIDeck deck: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAIDeck deck])",
returns = "nil"
},
setDepthMask = {
type = "method",
description = "Disables or enables depth writing.\n\n–> MOAIProp2D self\n[–> boolean depthMask: Default value is true.]\n<– nil",
args = "(MOAIProp2D self, [boolean depthMask])",
returns = "nil"
},
setDepthTest = {
type = "method",
description = "Sets and enables depth testing (assuming depth buffer is present).\n\n–> MOAIProp2D self\n[–> number depthFunc: Default value is MOAIProp2D.DEPTH_TEST_DISABLE.]\n<– nil",
args = "(MOAIProp2D self, [number depthFunc])",
returns = "nil"
},
setExpandForSort = {
type = "method",
description = "Used when drawing with a layout scheme (i.e. MOAIGrid). Expanding for sort causes the prop to emit a sub-prim for each component of the layout. For example, when attaching a MOAIGrid to a prop, each cell of the grid will be added to the render queue for sorting against all other props and sub-prims. This is obviously less efficient, but still more efficient then using an separate prop for each cell or object.\n\n–> MOAIProp2D self\n–> boolean expandForSort: Default value is false.\n<– nil",
args = "(MOAIProp2D self, boolean expandForSort)",
returns = "nil"
},
setFrame = {
type = "method",
description = "Sets the fitting frame of the prop.\n\nOverload:\n–> MOAIProp2D self\n<– nil\n\nOverload:\n–> MOAIProp2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIProp2D self, [number xMin, number yMin, number xMax, number yMax])",
returns = "nil"
},
setGrid = {
type = "method",
description = "Sets or clears the prop's grid indexer. The grid indexer (if any) will override the standard indexer.\n\n–> MOAIProp2D self\n[–> MOAIGrid grid: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAIGrid grid])",
returns = "nil"
},
setGridScale = {
type = "method",
description = "Scale applied to deck items before rendering to grid cell.\n\n–> MOAIProp2D self\n[–> number xScale: Default value is 1.]\n[–> number yScale: Default value is 1.]\n<– nil",
args = "(MOAIProp2D self, [number xScale, [number yScale]])",
returns = "nil"
},
setIndex = {
type = "method",
description = "Set the prop's index into its deck.\n\n–> MOAIProp2D self\n[–> number index: Default value is 1.]\n<– nil",
args = "(MOAIProp2D self, [number index])",
returns = "nil"
},
setParent = {
type = "method",
description = "This method has been deprecated. Use MOAINode setAttrLink instead.\n\n–> MOAIProp2D self\n[–> MOAINode parent: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAINode parent])",
returns = "nil"
},
setPriority = {
type = "method",
description = "Sets or clears the node's priority. Clear the priority to have MOAIPartition automatically assign a priority to a node when it is added.\n\n–> MOAIProp2D self\n[–> number priority: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [number priority])",
returns = "nil"
},
setRemapper = {
type = "method",
description = "Set a remapper for this prop to use when drawing deck members.\n\n–> MOAIProp2D self\n[–> MOAIDeckRemapper remapper: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAIDeckRemapper remapper])",
returns = "nil"
},
setShader = {
type = "method",
description = "Sets or clears the prop's shader. The prop's shader takes precedence over any shader specified by the deck or its elements.\n\n–> MOAIProp2D self\n[–> MOAIShader shader: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAIShader shader])",
returns = "nil"
},
setTexture = {
type = "method",
description = "Set or load a texture for this prop. The prop's texture will override the deck's texture.\n\n–> MOAIProp2D self\n–> variant texture: A MOAITexture, MOAIMultiTexture, MOAIDataBuffer or a path to a texture file\n[–> number transform: Any bitwise combination of MOAITextureBase.QUANTIZE, MOAITextureBase.TRUECOLOR, MOAITextureBase.PREMULTIPLY_ALPHA]\n<– MOAIGfxState texture",
args = "(MOAIProp2D self, variant texture, [number transform])",
returns = "MOAIGfxState texture",
valuetype = "MOAIGfxState"
},
setUVTransform = {
type = "method",
description = "Sets or clears the prop's UV transform.\n\n–> MOAIProp2D self\n[–> MOAITransformBase transform: Default value is nil.]\n<– nil",
args = "(MOAIProp2D self, [MOAITransformBase transform])",
returns = "nil"
},
setVisible = {
type = "method",
description = "Sets or clears the prop's visibility.\n\n–> MOAIProp2D self\n[–> boolean visible: Default value is true.]\n<– nil",
args = "(MOAIProp2D self, [boolean visible])",
returns = "nil"
}
}
},
MOAIRenderable = {
type = "class",
inherits = "MOAILuaObject",
description = "Abstract base class for objects that can be rendered by MOAIRenderMgr.",
childs = {}
},
MOAIRenderMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "MOAIRenderMgr is responsible for drawing a list of MOAIRenderable objects. MOAIRenderable is the base class for any object that can be drawn. This includes MOAIProp and MOAILayer. To use MOAIRenderMgr pass a table of MOAIRenderable objects to MOAIRenderMgr.setRenderTable (). The table will usually be a stack of MOAILayer objects. The contents of the table will be rendered the next time a frame is drawn. Note that the table must be an array starting with index 1. Objects will be rendered counting from the base index until 'nil' is encountered. The render table may include other tables as entries. These must also be arrays indexed from 1.",
childs = {
clearRenderStack = {
type = "function",
description = "Sets the render stack to nil. THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n<– nil",
args = "()",
returns = "nil"
},
getPerformanceDrawCount = {
type = "function",
description = 'Returns the number of draw calls last frame.\n\n<– number count: Number of underlying graphics "draw" calls last frame.',
args = "()",
returns = "number count",
valuetype = "number"
},
getRenderTable = {
type = "function",
description = "Returns the table currently being used for rendering.\n\n<– table renderTable",
args = "()",
returns = "table renderTable",
valuetype = "table"
},
grabNextFrame = {
type = "function",
description = "Save the next frame rendered to\n\n–> MOAIImage image: Image to save the backbuffer to\n–> function callback: The function to execute when the frame has been saved into the image specified\n<– table renderTable",
args = "(MOAIImage image, function callback)",
returns = "table renderTable",
valuetype = "table"
},
popRenderPass = {
type = "function",
description = "Pops the top renderable from the render stack. THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n<– nil",
args = "()",
returns = "nil"
},
pushRenderPass = {
type = "function",
description = "Pushes a renderable onto the render stack. THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n–> MOAIRenderable renderable\n<– nil",
args = "MOAIRenderable renderable",
returns = "nil"
},
removeRenderPass = {
type = "function",
description = "Removes a renderable from the render stack. THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE. Superseded by setRenderTable.\n\n–> MOAIRenderable renderable\n<– nil",
args = "MOAIRenderable renderable",
returns = "nil"
},
setRenderTable = {
type = "function",
description = "Sets the table to be used for rendering. This should be an array indexed from 1 consisting of MOAIRenderable objects and sub-tables. Objects will be rendered in order starting from index 1 and continuing until 'nil' is encountered.\n\n–> table renderTable\n<– nil",
args = "table renderTable",
returns = "nil"
}
}
},
MOAIScissorRect = {
type = "class",
inherits = "MOAITransform",
description = "Class for clipping props when drawing.",
childs = {
getRect = {
type = "method",
description = "Return the extents of the scissor rect.\n\n–> MOAIScissorRect self\n<– number xMin\n<– number yMin\n<– number xMax\n<– number yMax",
args = "MOAIScissorRect self",
returns = "(number xMin, number yMin, number xMax, number yMax)",
valuetype = "number"
},
setRect = {
type = "function",
description = "Sets the extents of the scissor rect.\n\n–> number x1: The X coordinate of the rect's upper-left point.\n–> number y1: The Y coordinate of the rect's upper-left point.\n–> number x2: The X coordinate of the rect's lower-right point.\n–> number y2: The Y coordinate of the rect's lower-right point.\n<– nil",
args = "(number x1, number y1, number x2, number y2)",
returns = "nil"
},
setScissorRect = {
type = "method",
description = "Set or clear the parent scissor rect.\n\n–> MOAIScissorRect self\n[–> MOAIScissorRect parent: Default value is nil.]\n<– nil",
args = "(MOAIScissorRect self, [MOAIScissorRect parent])",
returns = "nil"
}
}
},
MOAIScriptDeck = {
type = "class",
inherits = "MOAIDeck",
description = "Scriptable deck object.",
childs = {
setDrawCallback = {
type = "method",
description = "Sets the callback to be issued when draw events occur. The callback's parameters are ( number index, number xOff, number yOff, number xScale, number yScale ).\n\n–> MOAIScriptDeck self\n–> function callback\n<– nil",
args = "(MOAIScriptDeck self, function callback)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the model space dimensions of the deck's default rect.\n\n–> MOAIScriptDeck self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIScriptDeck self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setRectCallback = {
type = "method",
description = "Sets the callback to be issued when the size of a deck item needs to be determined. The callback's parameters are ( number index ).\n\n–> MOAIScriptDeck self\n–> function callback\n<– nil",
args = "(MOAIScriptDeck self, function callback)",
returns = "nil"
},
setTotalRectCallback = {
type = "method",
description = "Sets the callback to be issued when the size of a deck item needs to be determined. The callback's parameters are ( ).\n\n–> MOAIScriptDeck self\n–> function callback\n<– nil",
args = "(MOAIScriptDeck self, function callback)",
returns = "nil"
}
}
},
MOAIScriptNode = {
type = "class",
inherits = "MOAINode",
description = "User scriptable dependency node. User may specify Lua callback to handle node updating as well as custom floating point attributes.",
childs = {
reserveAttrs = {
type = "method",
description = "Reserve memory for custom attributes and initializes them to 0.\n\n–> MOAIScriptNode self\n–> number nAttributes\n<– nil",
args = "(MOAIScriptNode self, number nAttributes)",
returns = "nil"
},
setCallback = {
type = "method",
description = "Sets a Lua function to be called whenever the node is updated.\n\n–> MOAIScriptNode self\n–> function onUpdate\n<– nil",
args = "(MOAIScriptNode self, function onUpdate)",
returns = "nil"
}
}
},
MOAISensor = {
type = "class",
inherits = "MOAILuaObject",
description = "Base class for sensors.",
childs = {}
},
MOAISerializer = {
type = "class",
inherits = "MOAISerializerBase",
description = "Manages serialization state of Lua tables and Moai objects. The serializer will produce a Lua script that, when executed, will return the ordered list of objects added to it using the serialize () function.",
childs = {
exportToFile = {
type = "method",
description = "Exports the contents of the serializer to a file.\n\n–> MOAISerializer self\n–> string filename\n<– nil",
args = "(MOAISerializer self, string filename)",
returns = "nil"
},
exportToString = {
type = "method",
description = "Exports the contents of the serializer to a string.\n\n–> MOAISerializer self\n<– string result",
args = "MOAISerializer self",
returns = "string result",
valuetype = "string"
},
serialize = {
type = "method",
description = "Adds a table or object to the serializer.\n\nOverload:\n–> MOAISerializer self\n–> table data: The table to serialize.\n<– nil\n\nOverload:\n–> MOAISerializer self\n–> MOAILuaObject data: The object to serialize.\n<– nil",
args = "(MOAISerializer self, (table data | MOAILuaObject data))",
returns = "nil"
},
serializeToFile = {
type = "function",
description = "Serializes the specified table or object to a file.\n\nOverload:\n–> string filename: The file to create.\n–> table data: The table to serialize.\n<– nil\n\nOverload:\n–> string filename: The file to create.\n–> MOAILuaObject data: The object to serialize.\n<– nil",
args = "(string filename, (table data | MOAILuaObject data))",
returns = "nil"
},
serializeToString = {
type = "function",
description = "Serializes the specified table or object to a string.\n\nOverload:\n–> table data: The table to serialize.\n<– string serialized: The serialized string.\n\nOverload:\n–> MOAILuaObject data: The object to serialize.\n<– string serialized: The serialized string.",
args = "(table data | MOAILuaObject data)",
returns = "string serialized",
valuetype = "string"
}
}
},
MOAISerializerBase = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAIShader = {
type = "class",
inherits = "MOAINode MOAIGfxResource",
description = "Programmable shader class.",
childs = {
UNIFORM_COLOR = {
type = "value"
},
UNIFORM_FLOAT = {
type = "value"
},
UNIFORM_INT = {
type = "value"
},
UNIFORM_PEN_COLOR = {
type = "value"
},
UNIFORM_SAMPLER = {
type = "value"
},
UNIFORM_TRANSFORM = {
type = "value"
},
UNIFORM_VIEW_PROJ = {
type = "value"
},
UNIFORM_WORLD = {
type = "value"
},
UNIFORM_WORLD_VIEW = {
type = "value"
},
UNIFORM_WORLD_VIEW_PROJ = {
type = "value"
},
clearUniform = {
type = "method",
description = "Clears a uniform mapping.\n\n–> MOAIShader self\n–> number idx\n<– nil",
args = "(MOAIShader self, number idx)",
returns = "nil"
},
declareUniform = {
type = "method",
description = "Declares a uniform mapping.\n\n–> MOAIShader self\n–> number idx\n–> string name\n[–> number type: One of MOAIShader.UNIFORM_COLOR, MOAIShader.UNIFORM_FLOAT, MOAIShader.UNIFORM_INT, MOAIShader.UNIFORM_TRANSFORM, MOAIShader.UNIFORM_PEN_COLOR, MOAIShader.UNIFORM_VIEW_PROJ, MOAIShader.UNIFORM_WORLD, MOAIShader.UNIFORM_WORLD_VIEW, MOAIShader.UNIFORM_WORLD_VIEW_PROJ]\n<– nil",
args = "(MOAIShader self, number idx, string name, [number type])",
returns = "nil"
},
declareUniformFloat = {
type = "method",
description = "Declares an float uniform.\n\n–> MOAIShader self\n–> number idx\n–> string name\n[–> number value: Default value is 0.]\n<– nil",
args = "(MOAIShader self, number idx, string name, [number value])",
returns = "nil"
},
declareUniformInt = {
type = "method",
description = "Declares an integer uniform.\n\n–> MOAIShader self\n–> number idx\n–> string name\n[–> number value: Default value is 0.]\n<– nil",
args = "(MOAIShader self, number idx, string name, [number value])",
returns = "nil"
},
declareUniformSampler = {
type = "method",
description = "Declares an uniform to be used as a texture unit index. This uniform is internally an int, but when loaded into the shader the number one subtracted from its value. This allows the user to maintain consistency with Lua's convention of indexing from one.\n\n–> MOAIShader self\n–> number idx\n–> string name\n[–> number textureUnit: Default value is 1.]\n<– nil",
args = "(MOAIShader self, number idx, string name, [number textureUnit])",
returns = "nil"
},
load = {
type = "method",
description = "Load a shader program.\n\n–> MOAIShader self\n–> string vertexShaderSource\n–> string fragmentShaderSource\n<– nil",
args = "(MOAIShader self, string vertexShaderSource, string fragmentShaderSource)",
returns = "nil"
},
reserveUniforms = {
type = "method",
description = "Reserve shader uniforms.\n\n–> MOAIShader self\n[–> number nUniforms: Default value is 0.]\n<– nil",
args = "(MOAIShader self, [number nUniforms])",
returns = "nil"
},
setVertexAttribute = {
type = "method",
description = "Names a shader vertex attribute.\n\n–> MOAIShader self\n–> number index: Default value is 1.\n–> string name: Name of attribute.\n<– nil",
args = "(MOAIShader self, number index, string name)",
returns = "nil"
}
}
},
MOAIShaderMgr = {
type = "class",
inherits = "MOAILuaObject",
description = "Shader presets.",
childs = {
DECK2D_SHADER = {
type = "value"
},
DECK2D_TEX_ONLY_SHADER = {
type = "value"
},
FONT_SHADER = {
type = "value"
},
LINE_SHADER = {
type = "value"
},
MESH_SHADER = {
type = "value"
},
getShader = {
type = "function",
description = "Return one of the built-in shaders.\n\n–> number shaderID: One of MOAIShaderMgr.DECK2D_SHADER, MOAIShaderMgr.FONT_SHADER, MOAIShaderMgr.LINE_SHADER, MOAIShaderMgr.MESH_SHADER\n<– nil",
args = "number shaderID",
returns = "nil"
}
}
},
MOAISim = {
type = "class",
inherits = "MOAILuaObject",
description = "Sim timing and settings class.",
childs = {
DEFAULT_BOOST_THRESHOLD = {
type = "value",
description = "Value is 3"
},
DEFAULT_CPU_BUDGET = {
type = "value",
description = "Value is 2"
},
DEFAULT_LONG_DELAY_THRESHOLD = {
type = "value",
description = "Value is 10"
},
DEFAULT_STEP_MULTIPLIER = {
type = "value",
description = "Value is 1"
},
DEFAULT_STEPS_PER_SECOND = {
type = "value",
description = "Value is 60"
},
EVENT_FINALIZE = {
type = "value"
},
EVENT_PAUSE = {
type = "value"
},
EVENT_RESUME = {
type = "value"
},
LOOP_FLAGS_DEFAULT = {
type = "value"
},
LOOP_FLAGS_FIXED = {
type = "value"
},
LOOP_FLAGS_MULTISTEP = {
type = "value"
},
SIM_LOOP_ALLOW_BOOST = {
type = "value"
},
SIM_LOOP_ALLOW_SOAK = {
type = "value"
},
SIM_LOOP_ALLOW_SPIN = {
type = "value"
},
SIM_LOOP_FORCE_STEP = {
type = "value"
},
SIM_LOOP_NO_DEFICIT = {
type = "value"
},
SIM_LOOP_NO_SURPLUS = {
type = "value"
},
SIM_LOOP_RESET_CLOCK = {
type = "value"
},
clearLoopFlags = {
type = "function",
description = "Uses the mask provided to clear the loop flags.\n\n[–> number mask: Default value is 0xffffffff.]\n<– nil",
args = "[number mask]",
returns = "nil"
},
clearRenderStack = {
type = "function",
description = "Alias for MOAIRenderMgr.clearRenderStack (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n<– nil",
args = "()",
returns = "nil"
},
crash = {
type = "function",
description = "Crashes Moai with a null pointer dereference.\n\n<– nil",
args = "()",
returns = "nil"
},
enterFullscreenMode = {
type = "function",
description = "Enters fullscreen mode on the device if possible.\n\n<– nil",
args = "()",
returns = "nil"
},
exitFullscreenMode = {
type = "function",
description = "Exits fullscreen mode on the device if possible.\n\n<– nil",
args = "()",
returns = "nil"
},
forceGC = {
type = "function",
description = "Runs the garbage collector repeatedly until no more MOAIObjects can be collected.\n\n<– nil",
args = "()",
returns = "nil"
},
framesToTime = {
type = "function",
description = "Converts the number of frames to time passed in seconds.\n\n–> number frames: The number of frames.\n<– number time: The equivalent number of seconds for the specified number of frames.",
args = "number frames",
returns = "number time",
valuetype = "number"
},
getDeviceTime = {
type = "function",
description = "Gets the raw device clock. This is a replacement for Lua's os.time ().\n\n<– number time: The device clock time in seconds.",
args = "()",
returns = "number time",
valuetype = "number"
},
getElapsedFrames = {
type = "function",
description = "Gets the number of frames elapsed since the application was started.\n\n<– number frames: The number of elapsed frames.",
args = "()",
returns = "number frames",
valuetype = "number"
},
getElapsedTime = {
type = "function",
description = "Gets the number of seconds elapsed since the application was started.\n\n<– number time: The number of elapsed seconds.",
args = "()",
returns = "number time",
valuetype = "number"
},
getHistogram = {
type = "function",
description = "Generates a histogram of active MOAIObjects and returns it in a table containing object tallies indexed by object class names.\n\n<– table histogram",
args = "()",
returns = "table histogram",
valuetype = "table"
},
getLoopFlags = {
type = "function",
description = "Returns the current loop flags.\n\n<– number mask",
args = "()",
returns = "number mask",
valuetype = "number"
},
getLuaObjectCount = {
type = "function",
description = "Gets the total number of objects in memory that inherit MOAILuaObject. Count includes objects that are not bound to the Lua runtime.\n\n<– number count",
args = "()",
returns = "number count",
valuetype = "number"
},
getMemoryUsage = {
type = "function",
description = "Get the current amount of memory used by MOAI and its subsystems. This will attempt to return reasonable estimates where exact values cannot be obtained. Some fields represent informational fields (i.e. are not double counted in the total, but present to assist debugging) and may be only available on certain platforms (e.g. Windows, etc). These fields begin with a '_' character.\n\n<– table usage: The breakdown of each subsystem's memory usage, in bytes. There is also a \"total\" field that contains the summed value.",
args = "()",
returns = "table usage",
valuetype = "table"
},
getPerformance = {
type = "function",
description = "Returns an estimated frames per second based on measurements taken at every render.\n\n<– number fps: Estimated frames per second.",
args = "()",
returns = "number fps",
valuetype = "number"
},
getStep = {
type = "function",
description = "Gets the amount of time (in seconds) that it takes for one frame to pass.\n\n<– number size: The size of the frame; the time it takes for one frame to pass.",
args = "()",
returns = "number size",
valuetype = "number"
},
hideCursor = {
type = "function",
description = "Hides system cursor.\n\n<– nil",
args = "()",
returns = "nil"
},
openWindow = {
type = "function",
description = "Opens a new window for the application to render on. This must be called before any rendering can be done, and it must only be called once.\n\n–> string title: The title of the window.\n–> number width: The width of the window in pixels.\n–> number height: The height of the window in pixels.\n<– nil",
args = "(string title, number width, number height)",
returns = "nil"
},
pauseTimer = {
type = "function",
description = "Pauses or unpauses the device timer, preventing any visual updates (rendering) while paused.\n\n–> boolean pause: Whether the device timer should be paused.\n<– nil",
args = "boolean pause",
returns = "nil"
},
popRenderPass = {
type = "function",
description = "Alias for MOAIRenderMgr.popRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n<– nil",
args = "()",
returns = "nil"
},
pushRenderPass = {
type = "function",
description = "Alias for MOAIRenderMgr.pushRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n–> MOAIRenderable renderable\n<– nil",
args = "MOAIRenderable renderable",
returns = "nil"
},
removeRenderPass = {
type = "function",
description = "Alias for MOAIRenderMgr.removeRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE.\n\n–> MOAIRenderable renderable\n<– nil",
args = "MOAIRenderable renderable",
returns = "nil"
},
reportHistogram = {
type = "function",
description = "Generates a histogram of active MOAIObjects.\n\n<– nil",
args = "()",
returns = "nil"
},
reportLeaks = {
type = "function",
description = 'Analyze the currently allocated MOAI objects and create a textual report of where they were declared, and what Lua references (if any) can be found. NOTE: This is incredibly slow, so only use to debug leaking memory issues. This will also trigger a full garbage collection before performing the required report. (Equivalent of collectgarbage("collect").)\n\n–> boolean clearAfter: If true, it will reset the allocation tables (without freeing the underlying objects). This allows this method to be called after a known operation and get only those allocations created since the last call to this function.\n<– nil',
args = "boolean clearAfter",
returns = "nil"
},
setBoostThreshold = {
type = "function",
description = "Sets the boost threshold, a scalar applied to step. If the gap between simulation time and device time is greater than the step size multiplied by the boost threshold and MOAISim.SIM_LOOP_ALLOW_BOOST is set in the loop flags, then the simulation is updated once with a large, variable step to make up the entire gap.\n\n[–> number boostThreshold: Default value is DEFAULT_BOOST_THRESHOLD.]\n<– nil",
args = "[number boostThreshold]",
returns = "nil"
},
setCpuBudget = {
type = "function",
description = "Sets the amount of time (given in simulation steps) to allow for updating the simulation.\n\n–> number budget: Default value is DEFAULT_CPU_BUDGET.\n<– nil",
args = "number budget",
returns = "nil"
},
setHistogramEnabled = {
type = "function",
description = "Enable tracking of every MOAILuaObject so that an object count histogram may be generated.\n\n[–> boolean enable: Default value is false.]\n<– nil",
args = "[boolean enable]",
returns = "nil"
},
setLeakTrackingEnabled = {
type = "function",
description = "Enable extra memory book-keeping measures that allow all MOAI objects to be tracked back to their point of allocation (in Lua). Use together with MOAISim.reportLeaks() to determine exactly where your memory usage is being created. NOTE: This is very expensive in terms of both CPU and the extra memory associated with the stack info book-keeping. Use only when tracking down leaks.\n\n[–> boolean enable: Default value is false.]\n<– nil",
args = "[boolean enable]",
returns = "nil"
},
setLongDelayThreshold = {
type = "function",
description = "Sets the long delay threshold. If the simulation step falls behind the given threshold, the deficit will be dropped: the simulation will neither spin nor boost to catch up.\n\n[–> number longDelayThreshold: Default value is DEFAULT_LONG_DELAY_THRESHOLD.]\n<– nil",
args = "[number longDelayThreshold]",
returns = "nil"
},
setLoopFlags = {
type = "function",
description = "Fine tune behavior of the simulation loop. MOAISim.SIM_LOOP_ALLOW_SPIN will allow the simulation step to run multiple times per update to try and catch up with device time, but will abort if processing the simulation exceeds the configured step time. MOAISim.SIM_LOOP_ALLOW_BOOST will permit a *variable* update step if simulation time falls too far behind device time (based on the boost threshold). Be warned: this can wreak havoc with physics and stepwise animation or game AI. Three presets are provided: MOAISim.LOOP_FLAGS_DEFAULT, MOAISim.LOOP_FLAGS_FIXED, and MOAISim.LOOP_FLAGS_MULTISTEP.\n\n[–> number flags: Mask or a combination of MOAISim.SIM_LOOP_FORCE_STEP, MOAISim.SIM_LOOP_ALLOW_BOOST, MOAISim.SIM_LOOP_ALLOW_SPIN, MOAISim.SIM_LOOP_NO_DEFICIT, MOAISim.SIM_LOOP_NO_SURPLUS, MOAISim.SIM_LOOP_RESET_CLOCK. Default value is 0.]\n<– nil",
args = "[number flags]",
returns = "nil"
},
setLuaAllocLogEnabled = {
type = "function",
description = "Toggles log messages from Lua allocator.\n\n[–> boolean enable: Default value is 'false.']\n<– nil",
args = "[boolean enable]",
returns = "nil"
},
setStep = {
type = "function",
description = "Sets the size of each simulation step (in seconds).\n\n–> number step: The step size. Default value is 1 / DEFAULT_STEPS_PER_SECOND.\n<– nil",
args = "number step",
returns = "nil"
},
setStepMultiplier = {
type = "function",
description = "Runs the simulation multiple times per step (but with a fixed step size). This is used to speed up the simulation without providing a larger step size (which could destabilize physics simulation).\n\n–> number count: Default value is DEFAULT_STEP_MULTIPLIER.\n<– nil",
args = "number count",
returns = "nil"
},
setTimerError = {
type = "function",
description = "Sets the tolerance for timer error. This is a multiplier of step. Timer error tolerance is step * timerError.\n\n–> number timerError: Default value is 0.0.\n<– nil",
args = "number timerError",
returns = "nil"
},
setTraceback = {
type = "function",
description = "Sets the function to call when a traceback occurs in Lua\n\n–> function callback: Function to execute when the traceback occurs\n<– nil",
args = "function callback",
returns = "nil"
},
showCursor = {
type = "function",
description = "Shows system cursor.\n\n<– nil",
args = "()",
returns = "nil"
},
timeToFrames = {
type = "function",
description = "Converts the number of time passed in seconds to frames.\n\n–> number time: The number of seconds.\n<– number frames: The equivalent number of frames for the specified number of seconds.",
args = "number time",
returns = "number frames",
valuetype = "number"
}
}
},
MOAIStaticGlyphCache = {
type = "class",
inherits = "MOAIGlyphCacheBase",
description = "This is the default implementation of a static glyph cache. All is does is accept an image via setImage () and create a set of textures from that image. It does not implement getImage ().",
childs = {}
},
MOAIStream = {
type = "class",
inherits = "MOAILuaObject",
description = "Interface for reading/writing binary data.",
childs = {
SEEK_CUR = {
type = "value"
},
SEEK_END = {
type = "value"
},
SEEK_SET = {
type = "value"
},
flush = {
type = "method",
description = "Forces any remaining buffered data into the stream.\n\n–> MOAIStream self\n<– nil",
args = "MOAIStream self",
returns = "nil"
},
getCursor = {
type = "method",
description = "Returns the current cursor position in the stream.\n\n–> MOAIStream self\n<– number cursor",
args = "MOAIStream self",
returns = "number cursor",
valuetype = "number"
},
getLength = {
type = "method",
description = "Returns the length of the stream.\n\n–> MOAIStream self\n<– number length",
args = "MOAIStream self",
returns = "number length",
valuetype = "number"
},
read = {
type = "method",
description = "Reads bytes from the stream.\n\n–> MOAIStream self\n[–> number byteCount: Number of bytes to read. Default value is the length of the stream.]\n<– string bytes: Data read from the stream.\n<– number actualByteCount: Size of data successfully read.",
args = "(MOAIStream self, [number byteCount])",
returns = "(string bytes, number actualByteCount)",
valuetype = "string"
},
read16 = {
type = "method",
description = "Reads a signed 16-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
read32 = {
type = "method",
description = "Reads a signed 32-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
read8 = {
type = "method",
description = "Reads a signed 8-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
readDouble = {
type = "method",
description = "Reads a 64-bit floating point value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
readFloat = {
type = "method",
description = "Reads a 32-bit floating point value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
readFormat = {
type = "method",
description = "Reads a series of values from the stream given a format string. Valid tokens for the format string are: u8 u16 u32 f d s8 s16 s32. Tokens may be optionally separated by spaces of commas.\n\n–> MOAIStream self\n–> string format\n<– ... values: Values read from the stream or 'nil'.\n<– number size: Number of bytes successfully read.",
args = "(MOAIStream self, string format)",
returns = "(... values, number size)",
valuetype = "..."
},
readU16 = {
type = "method",
description = "Reads an unsigned 16-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
readU32 = {
type = "method",
description = "Reads an unsigned 32-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
readU8 = {
type = "method",
description = "Reads an unsigned 8-bit value from the stream.\n\n–> MOAIStream self\n<– number value: Value from the stream.\n<– number size: Number of bytes successfully read.",
args = "MOAIStream self",
returns = "(number value, number size)",
valuetype = "number"
},
seek = {
type = "method",
description = "Repositions the cursor in the stream.\n\n–> MOAIStream self\n–> number offset: Value from the stream.\n[–> number mode: One of MOAIStream.SEEK_CUR, MOAIStream.SEEK_END, MOAIStream.SEEK_SET. Default value is MOAIStream.SEEK_SET.]\n<– nil",
args = "(MOAIStream self, number offset, [number mode])",
returns = "nil"
},
write = {
type = "method",
description = "Write binary data to the stream.\n\n–> MOAIStream self\n–> string bytes: Binary data to write.\n[–> number size: Number of bytes to write. Default value is the size of the string.]\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, string bytes, [number size])",
returns = "number size",
valuetype = "number"
},
write16 = {
type = "method",
description = "Writes a signed 16-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
write32 = {
type = "method",
description = "Writes a signed 32-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
write8 = {
type = "method",
description = "Writes a signed 8-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
writeDouble = {
type = "method",
description = "Writes a 64-bit floating point value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
writeFloat = {
type = "method",
description = "Writes a 32-bit floating point value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
writeFormat = {
type = "method",
description = "Writes a series of values to the stream given a format string. See 'readFormat' for a list of valid format tokens.\n\n–> MOAIStream self\n–> string format\n–> ... values: Values to be written to the stream.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, string format, ... values)",
returns = "number size",
valuetype = "number"
},
writeStream = {
type = "method",
description = "Reads bytes from the given stream into the calling stream.\n\n–> MOAIStream self\n–> MOAIStream stream: Value to write.\n[–> number size: Number of bytes to read/write. Default value is the length of the input stream.]\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, MOAIStream stream, [number size])",
returns = "number size",
valuetype = "number"
},
writeU16 = {
type = "method",
description = "Writes an unsigned 16-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
writeU32 = {
type = "method",
description = "Writes an unsigned 32-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
},
writeU8 = {
type = "method",
description = "Writes an unsigned 8-bit value to the stream.\n\n–> MOAIStream self\n–> number value: Value to write.\n<– number size: Number of bytes successfully written.",
args = "(MOAIStream self, number value)",
returns = "number size",
valuetype = "number"
}
}
},
MOAIStreamReader = {
type = "class",
inherits = "MOAIStream",
description = "MOAIStreamReader may be attached to another stream for the purpose of decoding and/or decompressing bytes read from that stream using a given algorithm (such as base64 or 'deflate').",
childs = {
close = {
type = "method",
description = "Detach the target stream. (This only detaches the target from the formatter; it does not also close the target stream).\n\n–> MOAIStreamReader self\n<– nil",
args = "MOAIStreamReader self",
returns = "nil"
},
openBase64 = {
type = "method",
description = "Open a base 64 formatted stream for reading (i.e. decode bytes from base64).\n\n–> MOAIStreamReader self\n–> MOAIStream target\n<– boolean success",
args = "(MOAIStreamReader self, MOAIStream target)",
returns = "boolean success",
valuetype = "boolean"
},
openDeflate = {
type = "method",
description = "Open a 'deflate' formatted stream for reading (i.e. decompress bytes using the 'deflate' algorithm).\n\n–> MOAIStreamReader self\n–> MOAIStream target\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– boolean success",
args = "(MOAIStreamReader self, MOAIStream target, [number windowBits])",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIStreamWriter = {
type = "class",
inherits = "MOAIStream",
description = "MOAIStreamWriter may be attached to another stream for the purpose of encoding and/or compressing bytes written to that stream using a given algorithm (such as base64 or 'deflate').",
childs = {
close = {
type = "method",
description = "Flush any remaining buffered data and detach the target stream. (This only detaches the target from the formatter; it does not also close the target stream).\n\n–> MOAIStreamWriter self\n<– nil",
args = "MOAIStreamWriter self",
returns = "nil"
},
openBase64 = {
type = "method",
description = "Open a base 64 formatted stream for writing (i.e. encode bytes to base64).\n\n–> MOAIStreamWriter self\n–> MOAIStream target\n<– boolean success",
args = "(MOAIStreamWriter self, MOAIStream target)",
returns = "boolean success",
valuetype = "boolean"
},
openDeflate = {
type = "method",
description = "Open a 'deflate' formatted stream for writing (i.e. compress bytes using the 'deflate' algorithm).\n\n–> MOAIStreamWriter self\n–> MOAIStream target\n[–> number level: The level used in the DEFLATE algorithm.]\n[–> number windowBits: The window bits used in the DEFLATE algorithm.]\n<– boolean success",
args = "(MOAIStreamWriter self, MOAIStream target, [number level, [number windowBits]])",
returns = "boolean success",
valuetype = "boolean"
}
}
},
MOAIStretchPatch2D = {
type = "class",
inherits = "MOAIDeck",
description = "Moai implementation of a 9-patch. Textured quad with any number of stretchable and non-stretchable 'bands.' Grid drawing not supported.",
childs = {
reserveColumns = {
type = "method",
description = "Reserve total columns in patch.\n\n–> MOAIStretchPatch2D self\n–> number nColumns\n<– nil",
args = "(MOAIStretchPatch2D self, number nColumns)",
returns = "nil"
},
reserveRows = {
type = "method",
description = "Reserve total rows in patch.\n\n–> MOAIStretchPatch2D self\n–> number nRows\n<– nil",
args = "(MOAIStretchPatch2D self, number nRows)",
returns = "nil"
},
reserveUVRects = {
type = "method",
description = "Reserve total UV rects in patch. When a patch is indexed it will change its UV rects.\n\n–> MOAIStretchPatch2D self\n–> number nUVRects\n<– nil",
args = "(MOAIStretchPatch2D self, number nUVRects)",
returns = "nil"
},
setColumn = {
type = "method",
description = "Set the stretch properties of a patch column.\n\n–> MOAIStretchPatch2D self\n–> number idx\n–> number weight\n–> boolean conStretch\n<– nil",
args = "(MOAIStretchPatch2D self, number idx, number weight, boolean conStretch)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the model space dimensions of the patch.\n\n–> MOAIStretchPatch2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIStretchPatch2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setRow = {
type = "method",
description = "Set the stretch properties of a patch row.\n\n–> MOAIStretchPatch2D self\n–> number idx\n–> number weight\n–> boolean conStretch\n<– nil",
args = "(MOAIStretchPatch2D self, number idx, number weight, boolean conStretch)",
returns = "nil"
},
setUVRect = {
type = "method",
description = "Set the UV space dimensions of the patch.\n\n–> MOAIStretchPatch2D self\n–> number idx\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAIStretchPatch2D self, number idx, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
}
}
},
MOAISurfaceDeck2D = {
type = "class",
inherits = "MOAIDeck",
description = "Deck of surface edge lists. Unused in this version of Moai.",
childs = {
reserveSurfaceLists = {
type = "method",
description = "Reserve surface lists for deck.\n\n–> MOAISurfaceDeck2D self\n–> number nLists\n<– nil",
args = "(MOAISurfaceDeck2D self, number nLists)",
returns = "nil"
},
reserveSurfaces = {
type = "method",
description = "Reserve surfaces for a given list in deck.\n\n–> MOAISurfaceDeck2D self\n–> number idx\n–> number nSurfaces\n<– nil",
args = "(MOAISurfaceDeck2D self, number idx, number nSurfaces)",
returns = "nil"
},
setSurface = {
type = "method",
description = "Set a surface in a surface list.\n\n–> MOAISurfaceDeck2D self\n–> number idx\n–> number surfaceIdx\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n<– nil",
args = "(MOAISurfaceDeck2D self, number idx, number surfaceIdx, number x0, number y0, number x1, number y1)",
returns = "nil"
}
}
},
MOAITapjoyAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Tapjoy integration on Android devices. Tapjoy provides a turnkey advertising platform that delivers cost-effective, high-value new users and helps apps make money. Exposed to Lua via MOAITapjoy on all mobile platforms.",
childs = {
TAPJOY_VIDEO_AD_BEGIN = {
type = "value",
description = "Event code for Tapjoy video ad playback begin. Unused."
},
TAPJOY_VIDEO_AD_CLOSE = {
type = "value",
description = "Event code for Tapjoy video ad playback completion."
},
TAPJOY_VIDEO_AD_ERROR = {
type = "value",
description = "Event code for Tapjoy video ad playback errors."
},
TAPJOY_VIDEO_AD_READY = {
type = "value",
description = "Event code for Tapjoy video ad playback availability."
},
TAPJOY_VIDEO_STATUS_MEDIA_STORAGE_UNAVAILABLE = {
type = "value",
description = "Error code for inadequate storage for video ad."
},
TAPJOY_VIDEO_STATUS_NETWORK_ERROR_ON_INIT_VIDEOS = {
type = "value",
description = "Error code for network error."
},
TAPJOY_VIDEO_STATUS_NO_ERROR = {
type = "value",
description = "Error code for success."
},
TAPJOY_VIDEO_STATUS_UNABLE_TO_PLAY_VIDEO = {
type = "value",
description = "Error code for playback error."
},
getUserId = {
type = "function",
description = "Gets the Tapjoy user ID.\n\n<– string userId",
args = "()",
returns = "string userId",
valuetype = "string"
},
init = {
type = "function",
description = "Initializes Tapjoy.\n\n–> string appId: Available in Tapjoy dashboard settings.\n–> string secretKey: Available in Tapjoy dashboard settings.\n<– nil",
args = "(string appId, string secretKey)",
returns = "nil"
},
initVideoAds = {
type = "function",
description = "Initializes Tapjoy to display video ads.\n\n[–> number count: The optional number of ads to cache. Default is Tapjoy dependent.]\n<– nil",
args = "[number count]",
returns = "nil"
},
showOffers = {
type = "function",
description = "Displays the Tapjoy marketplace.\n\n<– nil",
args = "()",
returns = "nil"
}
}
},
MOAITapjoyIOS = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Tapjoy integration on iOS devices. Tapjoy provides a turnkey advertising platform that delivers cost-effective, high-value new users and helps apps make money. Exposed to Lua via MOAITapjoy on all mobile platforms.",
childs = {
TAPJOY_VIDEO_AD_BEGIN = {
type = "value",
description = "Event code for Tapjoy video ad playback begin."
},
TAPJOY_VIDEO_AD_CLOSE = {
type = "value",
description = "Event code for Tapjoy video ad playback completion."
},
TAPJOY_VIDEO_AD_ERROR = {
type = "value",
description = "Event code for Tapjoy video ad playback errors. Unused."
},
TAPJOY_VIDEO_AD_READY = {
type = "value",
description = "Event code for Tapjoy video ad playback availability. Unused."
},
TAPJOY_VIDEO_STATUS_MEDIA_STORAGE_UNAVAILABLE = {
type = "value",
description = "Error code for inadequate storage for video ad. Unused."
},
TAPJOY_VIDEO_STATUS_NETWORK_ERROR_ON_INIT_VIDEOS = {
type = "value",
description = "Error code for network error. Unused."
},
TAPJOY_VIDEO_STATUS_NO_ERROR = {
type = "value",
description = "Error code for success. Unused."
},
TAPJOY_VIDEO_STATUS_UNABLE_TO_PLAY_VIDEO = {
type = "value",
description = "Error code for playback error. Unused."
}
}
},
MOAITextBox = {
type = "class",
inherits = "MOAIProp MOAIAction",
description = "The text box manages styling, laying out and displaying text. You can attach named styles to the text box to be applied to the text using style escapes. You can also inline style escapes to control color. Style escapes may be nested.\nTo attach a style to a text box use setStyle (). If you provide a name for the style then the style may be applied by name using a style escape. If you do not provide a name then the style will be used as the default style for the text box. The default style is the style that will be used when no style escapes are in effect.\nThe setFont () and setSize () methods are helpers that operate on the text box's default style. If no default style exists when these methods are called, one will be created.\nThere are three kinds of text escapes. The first takes the form of <styleName> where 'styleName' is the name of the style you provided via setStyle (). If there is no match for the name then the default style will be used.\nThe second form of style escape sets text color. It takes the form of <c:XXX> where 'XXX' is a hexadecimal number representing a color value. The hexadecimal number may be have from one up to eight digits, excluding five digit numbers. One and two digit numbers correspond to grayscale values of 4 and 8 bits of precision (16 or 256 levels) respectively. Three and four digit numbers represent RGB and RGBA colors at 4 bit precision. Six digits is RGB at 8 bits of precision. Seven digits is RGBA with 8 bits for RGB and 4 bits for A. Eight digits is RGBA with 8 bits for each component.\nThe final text escapes ends the current escape. It takes the form of </>. Including any additional text in this kind of escape is an error.\nYou may escape the '<' symbol itself by using an additional '<'. For example, '<<' will output '<'. '<<test>' will short circuit the style escape and output '<test>' in the displayed text.\nWhen using MOAITextBox with MOAIFont it's important to understand how and when glyphs are rendered. When you call setText () the text box's style goes to work. The entire string you provide is scanned and a 'style span' is created for each uniquely styled block of text. If you do not use any styles then there will be only one style span.\nOnce the text style has created style spans for your text, the spans themselves are scanned. Each span must specify a font to be used. All of the characters in the span are 'affirmed' by the font: if the glyphs for the characters have already been ripped then nothing happens. If not, the characters are enqueued by the font to have their glyphs ripped.\nFinally, we iterate through all of the fonts used by the text and instruct them to load and render any pending glyphs. If the font is dynamic and has a valid implementation of MOAIFontReader and MOAIGlyphCache attached to it then the glyphs will be rendered and placed in the cache.\nOnce the glyphs have been rendered, we know their metrics and (hopefully) have valid textures for them. We can now lay out an actual page of text. This is done by a separate subsystem known as the text designer. The text designer reads the style spans and uses the associated font, color and size information to place the glyphs into a layout.\nIf the text associated with the textbox doesn't fit, then the textbox will have multiple pages. The only method that deals with pages at this time is nextPage (). Additional methods giving finer control over multi-page text boxes will be provided in a future release.\nThere are some additional ways you can use the text box to style your text. The current implementation supports left, center and right positioning as well as top, center and bottom positioning. A future implementation will include justification in which words and lines of text will be spaced out to align with the edges of the text box.\nYou can also attach MOAIAnimCurves to the text box. The animation curves may be used to offset characters in lines of text. Each curve may have any number of keyframes, but only the span between t0 and t1 is used by the text box, regardless of its width. Curves correspond to lines of text. If there are more lines of text than curves, the curves will simply repeat.\nOnce you've loaded text into the text box you can apply highlight colors. These colors will override any colors specified by style escapes. Highlight spans may be set or cleared using setHighlight (). clearHighlights () will remove all highlights from the text. Highlights will persists from page to page of text, but will be lost if new text is loaded by calling setText ().",
childs = {
CENTER_JUSTIFY = {
type = "value"
},
LEFT_JUSTIFY = {
type = "value"
},
RIGHT_JUSTIFY = {
type = "value"
},
affirmStyle = {
type = "method",
description = "Returns the textbox's default style. If no default style exists, creates an empty style, sets it as the default and returns it.\n\n–> MOAITextBox self\n<– MOAITextStyle style",
args = "MOAITextBox self",
returns = "MOAITextStyle style",
valuetype = "MOAITextStyle"
},
clearHighlights = {
type = "method",
description = "Removes all highlights currently associated with the text box.\n\n–> MOAITextBox self\n<– nil",
args = "MOAITextBox self",
returns = "nil"
},
getAlignment = {
type = "method",
description = "Returns the alignment of the text\n\n–> MOAITextBox self\n<– number hAlign: horizontal alignment\n<– number vAlign: vertical alignment",
args = "MOAITextBox self",
returns = "(number hAlign, number vAlign)",
valuetype = "number"
},
getGlyphScale = {
type = "method",
description = "Returns the current glyph scale.\n\n–> MOAITextBox self\n<– number glyphScale",
args = "MOAITextBox self",
returns = "number glyphScale",
valuetype = "number"
},
getLineSpacing = {
type = "method",
description = "Returns the spacing between lines (in pixels).\n\n–> MOAITextBox self\n<– number lineScale: The size of the spacing in pixels.",
args = "MOAITextBox self",
returns = "number lineScale",
valuetype = "number"
},
getRect = {
type = "method",
description = "Returns the two-dimensional boundary of the text box.\n\n–> MOAITextBox self\n<– number xMin\n<– number yMin\n<– number xMax\n<– number yMax",
args = "MOAITextBox self",
returns = "(number xMin, number yMin, number xMax, number yMax)",
valuetype = "number"
},
getStringBounds = {
type = "method",
description = "Returns the bounding rectangle of a given substring on a single line in the local space of the text box.\n\n–> MOAITextBox self\n–> number index: Index of the first character in the substring.\n–> number size: Length of the substring.\n<– number xMin: Edge of rect or 'nil' is no match found.\n<– number yMin: Edge of rect or 'nil' is no match found.\n<– number xMax: Edge of rect or 'nil' is no match found.\n<– number yMax: Edge of rect or 'nil' is no match found.",
args = "(MOAITextBox self, number index, number size)",
returns = "(number xMin, number yMin, number xMax, number yMax)",
valuetype = "number"
},
getStyle = {
type = "method",
description = "Returns the style associated with a name or, if no name is given, returns the default style.\n\nOverload:\n–> MOAITextBox self\n<– MOAITextStyle defaultStyle\n\nOverload:\n–> MOAITextBox self\n–> string styleName\n<– MOAITextStyle style",
args = "(MOAITextBox self, [string styleName])",
returns = "(MOAITextStyle defaultStyle | MOAITextStyle style)",
valuetype = "MOAITextStyle"
},
more = {
type = "method",
description = "Returns whether there are additional pages of text below the cursor position that are not visible on the screen.\n\n–> MOAITextBox self\n<– boolean isMore: If there is additional text below the cursor that is not visible on the screen due to clipping.",
args = "MOAITextBox self",
returns = "boolean isMore",
valuetype = "boolean"
},
nextPage = {
type = "method",
description = "Advances to the next page of text (if any) or wraps to the start of the text (if at end).\n\n–> MOAITextBox self\n[–> boolean reveal: Default is true]\n<– nil",
args = "(MOAITextBox self, [boolean reveal])",
returns = "nil"
},
reserveCurves = {
type = "method",
description = "Reserves a set of IDs for animation curves to be binding to this text object. See setCurves.\n\n–> MOAITextBox self\n–> number nCurves\n<– nil",
args = "(MOAITextBox self, number nCurves)",
returns = "nil"
},
revealAll = {
type = "method",
description = "Displays as much text as will fit in the text box.\n\n–> MOAITextBox self\n<– nil",
args = "MOAITextBox self",
returns = "nil"
},
setAlignment = {
type = "method",
description = "Sets the horizontal and/or vertical alignment of the text in the text box.\n\n–> MOAITextBox self\n–> number hAlignment: Can be one of LEFT_JUSTIFY, CENTER_JUSTIFY or RIGHT_JUSTIFY.\n–> number vAlignment: Can be one of LEFT_JUSTIFY, CENTER_JUSTIFY or RIGHT_JUSTIFY.\n<– nil",
args = "(MOAITextBox self, number hAlignment, number vAlignment)",
returns = "nil"
},
setCurve = {
type = "method",
description = "Binds an animation curve to the text, where the Y value of the curve indicates the text offset, or clears the curves.\n\nOverload:\n–> MOAITextBox self\n–> number curveID: The ID of the curve within this text object.\n–> MOAIAnimCurve curve: The MOAIAnimCurve to bind to.\n<– nil\n\nOverload:\n–> MOAITextBox self\n<– nil",
args = "(MOAITextBox self, [number curveID, MOAIAnimCurve curve])",
returns = "nil"
},
setFont = {
type = "method",
description = "Sets the font to be used by the textbox's default style. If no default style exists, a default style is created.\n\n–> MOAITextBox self\n–> MOAIFont font\n<– nil",
args = "(MOAITextBox self, MOAIFont font)",
returns = "nil"
},
setGlyphScale = {
type = "method",
description = "Sets the glyph scale. This is a scalar applied to glyphs as they are positioned in the text box.\n\n–> MOAITextBox self\n[–> number glyphScale: Default value is 1.]\n<– number glyphScale",
args = "(MOAITextBox self, [number glyphScale])",
returns = "number glyphScale",
valuetype = "number"
},
setHighlight = {
type = "method",
description = "Set or clear the highlight color of a sub string in the text. Only affects text displayed on the current page. Highlight will automatically clear when layout or page changes.\n\nOverload:\n–> MOAITextBox self\n–> number index: Index of the first character in the substring.\n–> number size: Length of the substring.\n–> number r\n–> number g\n–> number b\n[–> number a: Default value is 1.]\n<– nil\n\nOverload:\n–> MOAITextBox self\n–> number index: Index of the first character in the substring.\n–> number size: Length of the substring.\n<– nil",
args = "(MOAITextBox self, number index, number size, [number r, number g, number b, [number a]])",
returns = "nil"
},
setLineSpacing = {
type = "method",
description = "Sets additional space between lines in text units. '0' uses the default spacing. Values must be positive.\n\n–> MOAITextBox self\n–> number lineSpacing: Default value is 0.\n<– nil",
args = "(MOAITextBox self, number lineSpacing)",
returns = "nil"
},
setRect = {
type = "method",
description = "Sets the rectangular area for this text box.\n\n–> MOAITextBox self\n–> number x1: The X coordinate of the rect's upper-left point.\n–> number y1: The Y coordinate of the rect's upper-left point.\n–> number x2: The X coordinate of the rect's lower-right point.\n–> number y2: The Y coordinate of the rect's lower-right point.\n<– nil",
args = "(MOAITextBox self, number x1, number y1, number x2, number y2)",
returns = "nil"
},
setReveal = {
type = "method",
description = "Sets the number of renderable characters to be shown. Can range from 0 to any value; values greater than the number of renderable characters in the current text will be ignored.\n\n–> MOAITextBox self\n–> number reveal: The number of renderable characters (i.e. not whitespace) to be shown.\n<– nil",
args = "(MOAITextBox self, number reveal)",
returns = "nil"
},
setSnapToViewportScale = {
type = "method",
description = "If set to true text positions will snap to integers according to the viewport scale. Default value is true.\n\n–> MOAITextBox self\n–> boolean snap: Whether text positions should snap to viewport scale\n<– nil",
args = "(MOAITextBox self, boolean snap)",
returns = "nil"
},
setSpeed = {
type = "method",
description = "Sets the base spool speed used when creating a spooling MOAIAction with the spool() function.\n\n–> MOAITextBox self\n–> number speed: The base spooling speed.\n<– nil",
args = "(MOAITextBox self, number speed)",
returns = "nil"
},
setString = {
type = "method",
description = "Sets the text string to be displayed by this textbox.\n\n–> MOAITextBox self\n–> string newStr: The new text string to be displayed.\n<– nil",
args = "(MOAITextBox self, string newStr)",
returns = "nil"
},
setStyle = {
type = "method",
description = "Attaches a style to the textbox and associates a name with it. If no name is given, sets the default style.\n\nOverload:\n–> MOAITextBox self\n–> MOAITextStyle defaultStyle\n<– nil\n\nOverload:\n–> MOAITextBox self\n–> string styleName\n–> MOAITextStyle style\n<– nil",
args = "(MOAITextBox self, (MOAITextStyle defaultStyle | (string styleName, MOAITextStyle style)))",
returns = "nil"
},
setTextSize = {
type = "method",
description = "Sets the size to be used by the textbox's default style. If no default style exists, a default style is created.\n\n–> MOAITextBox self\n–> number points: The point size to be used by the default style.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAITextBox self, number points, [number dpi])",
returns = "nil"
},
setWordBreak = {
type = "method",
description = "Sets the rule for breaking words across lines.\n\n–> MOAITextBox self\n[–> number rule: One of MOAITextBox.WORD_BREAK_NONE, MOAITextBox.WORD_BREAK_CHAR. Default is MOAITextBox.WORD_BREAK_NONE.]\n<– nil",
args = "(MOAITextBox self, [number rule])",
returns = "nil"
},
setYFlip = {
type = "method",
description = "Sets the rendering direction for the text. Default assumes a window style screen space (positive Y moves down the screen). Set to true to render text for world style coordinate systems (positive Y moves up the screen).\n\n–> MOAITextBox self\n–> boolean yFlip: Whether the vertical rendering direction should be inverted.\n<– nil",
args = "(MOAITextBox self, boolean yFlip)",
returns = "nil"
},
spool = {
type = "method",
description = "Creates a new MOAIAction which when run has the effect of increasing the amount of characters revealed from 0 to the length of the string currently set. The spool action is automatically added to the root of the action tree, but may be reparented or stopped by the developer. This function also automatically sets the current number of revealed characters to 0 (i.e. MOAITextBox:setReveal(0)).\n\n–> MOAITextBox self\n–> number yFlip: Whether the vertical rendering direction should be inverted.\n<– MOAIAction action: The new MOAIAction which spools the text when run.",
args = "(MOAITextBox self, number yFlip)",
returns = "MOAIAction action",
valuetype = "MOAIAction"
}
}
},
MOAITextBundle = {
type = "class",
inherits = "MOAILuaObject",
description = "A read-only lookup table of strings suitable for internationalization purposes. This currently wraps a loaded gettext() style MO file (see http://www.gnu.org/software/gettext/manual/gettext.html). So you are going to want to generate the .mo file from one of the existing tools such as poedit or msgfmt, and then load that file using this class. Then you can lookup strings using MOAITextBundle->Lookup().",
childs = {
load = {
type = "method",
description = "Load a text bundle from a .mo file.\n\nOverload:\n–> MOAITextBundle self\n–> MOAIDataBuffer buffer: A MOAIDataBuffer containing the text bundle.\n<– number size: The number of bytes in this data buffer object.\n\nOverload:\n–> MOAITextBundle self\n–> string filename: The filename to load.\n<– number size: The number of bytes in this data buffer object.",
args = "(MOAITextBundle self, (MOAIDataBuffer buffer | string filename))",
returns = "number size",
valuetype = "number"
},
lookup = {
type = "method",
description = 'Look up a string in the bundle (defaulting to the lookup string itself). In the case of defaulting, a false value is returned as the second value (useful for falling back to less-specific bundles if desirable).\n\n–> MOAITextBundle self\n–> string key: A text string to use as a "key"\n<– string value: The value if found, otherwise it returns the original string if not found.\n<– boolean found: True if the string was found in the table (regardless of returned value), or false if it couldn\'t be found.',
args = "(MOAITextBundle self, string key)",
returns = "(string value, boolean found)",
valuetype = "string"
}
}
},
MOAITextStyle = {
type = "class",
inherits = "MOAINode MOAITextStyleState",
description = "Represents a style that may be applied to a text box or a section of text in a text box using a style escape.",
childs = {
getColor = {
type = "method",
description = "Gets the color of the style.\n\n–> MOAITextStyle self\n<– number r\n<– number g\n<– number b\n<– number a",
args = "MOAITextStyle self",
returns = "(number r, number g, number b, number a)",
valuetype = "number"
},
getFont = {
type = "method",
description = "Gets the font of the style.\n\n–> MOAITextStyle self\n<– MOAIFont font",
args = "MOAITextStyle self",
returns = "MOAIFont font",
valuetype = "MOAIFont"
},
getScale = {
type = "method",
description = "Gets the scale of the style.\n\n–> MOAITextStyle self\n<– number scale",
args = "MOAITextStyle self",
returns = "number scale",
valuetype = "number"
},
getSize = {
type = "method",
description = "Gets the size of the style.\n\n–> MOAITextStyle self\n<– number size",
args = "MOAITextStyle self",
returns = "number size",
valuetype = "number"
},
setColor = {
type = "method",
description = "Initialize the style's color.\n\n–> MOAITextStyle self\n–> number r: Default value is 0.\n–> number g: Default value is 0.\n–> number b: Default value is 0.\n[–> number a: Default value is 1.]\n<– nil",
args = "(MOAITextStyle self, number r, number g, number b, [number a])",
returns = "nil"
},
setFont = {
type = "method",
description = "Sets or clears the style's font.\n\n–> MOAITextStyle self\n[–> MOAIFont font: Default value is nil.]\n<– nil",
args = "(MOAITextStyle self, [MOAIFont font])",
returns = "nil"
},
setScale = {
type = "method",
description = "Sets the scale of the style. The scale is applied to any glyphs drawn using the style after the glyph set has been selected by size.\n\n–> MOAITextStyle self\n[–> number scale: Default value is 1.]\n<– nil",
args = "(MOAITextStyle self, [number scale])",
returns = "nil"
},
setSize = {
type = "method",
description = "Sets or clears the style's size.\n\n–> MOAITextStyle self\n–> number points: The point size to be used by the style.\n[–> number dpi: The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).]\n<– nil",
args = "(MOAITextStyle self, number points, [number dpi])",
returns = "nil"
}
}
},
MOAITextStyleState = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
MOAITexture = {
type = "class",
inherits = "MOAITextureBase",
description = "Texture class.",
childs = {
load = {
type = "method",
description = "Loads a texture from a data buffer or a file. Optionally pass in an image transform (not applicable to PVR textures).\n\nOverload:\n–> MOAITexture self\n–> string filename\n[–> number transform: Any bitwise combination of MOAIImage.QUANTIZE, MOAIImage.TRUECOLOR, MOAIImage.PREMULTIPLY_ALPHA]\n[–> string debugname: Name used when reporting texture debug information]\n<– nil\n\nOverload:\n–> MOAITexture self\n–> MOAIImage image\n[–> string debugname: Name used when reporting texture debug information]\n<– nil\n\nOverload:\n–> MOAITexture self\n–> MOAIDataBuffer buffer\n[–> number transform: Any bitwise combination of MOAIImage.QUANTIZE, MOAIImage.TRUECOLOR, MOAIImage.PREMULTIPLY_ALPHA]\n[–> string debugname: Name used when reporting texture debug information]\n<– nil\n\nOverload:\n–> MOAITexture self\n–> MOAIStream buffer\n[–> number transform: Any bitwise combination of MOAIImage.QUANTIZE, MOAIImage.TRUECOLOR, MOAIImage.PREMULTIPLY_ALPHA]\n[–> string debugname: Name used when reporting texture debug information]\n<– nil"
}
}
},
MOAITextureBase = {
type = "class",
inherits = "MOAILuaObject MOAIGfxResource",
description = "Base class for texture resources.",
childs = {
GL_LINEAR = {
type = "value"
},
GL_LINEAR_MIPMAP_LINEAR = {
type = "value"
},
GL_LINEAR_MIPMAP_NEAREST = {
type = "value"
},
GL_NEAREST = {
type = "value"
},
GL_NEAREST_MIPMAP_LINEAR = {
type = "value"
},
GL_NEAREST_MIPMAP_NEAREST = {
type = "value"
},
getSize = {
type = "method",
description = "Returns the width and height of the texture's source image. Avoid using the texture width and height to compute UV coordinates from pixels, as this will prevent texture resolution swapping.\n\n–> MOAITextureBase self\n<– number width\n<– number height",
args = "MOAITextureBase self",
returns = "(number width, number height)",
valuetype = "number"
},
release = {
type = "method",
description = "Releases any memory associated with the texture.\n\n–> MOAITextureBase self\n<– nil",
args = "MOAITextureBase self",
returns = "nil"
},
setFilter = {
type = "method",
description = "Set default filtering mode for texture.\n\n–> MOAITextureBase self\n–> number min: One of MOAITextureBase.GL_LINEAR, MOAITextureBase.GL_LINEAR_MIPMAP_LINEAR, MOAITextureBase.GL_LINEAR_MIPMAP_NEAREST, MOAITextureBase.GL_NEAREST, MOAITextureBase.GL_NEAREST_MIPMAP_LINEAR, MOAITextureBase.GL_NEAREST_MIPMAP_NEAREST\n[–> number mag: Defaults to value passed to 'min'.]\n<– nil",
args = "(MOAITextureBase self, number min, [number mag])",
returns = "nil"
},
setWrap = {
type = "method",
description = "Set wrapping mode for texture.\n\n–> MOAITextureBase self\n–> boolean wrap: Texture will wrap if true, clamp if not.\n<– nil",
args = "(MOAITextureBase self, boolean wrap)",
returns = "nil"
}
}
},
MOAITileDeck2D = {
type = "class",
inherits = "MOAIDeck MOAIGridSpace",
description = "Subdivides a single texture into uniform tiles enumerated from the texture's left top to right bottom.",
childs = {
setQuad = {
type = "method",
description = "Set model space quad. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAITileDeck2D self\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAITileDeck2D self, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setRect = {
type = "method",
description = "Set the model space dimensions of a single tile. When grid drawing, this should be a unit rect centered at the origin for tiles that fit each grid cell. Growing or shrinking the rect will cause tiles to overlap or leave gaps between them.\n\n–> MOAITileDeck2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAITileDeck2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
setSize = {
type = "method",
description = "Controls how the texture is subdivided into tiles. Default behavior is to subdivide the texture into N by M tiles, but is tile dimensions are provided (in UV space) then the resulting tile set will be N * tileWidth by M * tileHeight in UV space. This means the tile set does not have to fill all of the texture. The upper left hand corner of the tile set will always be at UV 0, 0.\n\n–> MOAITileDeck2D self\n–> number width: Width of the tile deck in tiles.\n–> number height: Height of the tile deck in tiles.\n[–> number cellWidth: Width of individual tile in UV space. Defaults to 1 / width.]\n[–> number cellHeight: Height of individual tile in UV space. Defaults to 1 / height.]\n[–> number xOff: X offset of the tile from the cell. Defaults to 0.]\n[–> number yOff: Y offset of the tile from the cell. Defaults to 0.]\n[–> number tileWidth: Default value is cellWidth.]\n[–> number tileHeight: Default value is cellHeight.]\n<– nil",
args = "(MOAITileDeck2D self, number width, number height, [number cellWidth, [number cellHeight, [number xOff, [number yOff, [number tileWidth, [number tileHeight]]]]]])",
returns = "nil"
},
setUVQuad = {
type = "method",
description = "Set the UV space dimensions of the quad. Vertex order is clockwise from upper left (xMin, yMax)\n\n–> MOAITileDeck2D self\n–> number x0\n–> number y0\n–> number x1\n–> number y1\n–> number x2\n–> number y2\n–> number x3\n–> number y3\n<– nil",
args = "(MOAITileDeck2D self, number x0, number y0, number x1, number y1, number x2, number y2, number x3, number y3)",
returns = "nil"
},
setUVRect = {
type = "method",
description = "Set the UV space dimensions of the quad.\n\n–> MOAITileDeck2D self\n–> number xMin\n–> number yMin\n–> number xMax\n–> number yMax\n<– nil",
args = "(MOAITileDeck2D self, number xMin, number yMin, number xMax, number yMax)",
returns = "nil"
},
transform = {
type = "method",
description = "Apply the given MOAITransform to all the vertices in the deck.\n\n–> MOAITileDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAITileDeck2D self, MOAITransform transform)",
returns = "nil"
},
transformUV = {
type = "method",
description = "Apply the given MOAITransform to all the uv coordinates in the deck.\n\n–> MOAITileDeck2D self\n–> MOAITransform transform\n<– nil",
args = "(MOAITileDeck2D self, MOAITransform transform)",
returns = "nil"
}
}
},
MOAITimer = {
type = "class",
inherits = "MOAINode MOAIAction",
description = "Timer class for driving curves and animations.",
childs = {
ATTR_TIME = {
type = "value"
},
CONTINUE = {
type = "value"
},
CONTINUE_REVERSE = {
type = "value"
},
EVENT_TIMER_BEGIN_SPAN = {
type = "value",
description = "Called when timer starts or after roll over (if looping). Signature is: nil onBeginSpan ( MOAITimer self, number timesExecuted )"
},
EVENT_TIMER_END_SPAN = {
type = "value",
description = "Called when timer ends or before roll over (if looping). Signature is: nil onEndSpan ( MOAITimer self, number timesExecuted )"
},
EVENT_TIMER_KEYFRAME = {
type = "value",
description = "ID of event stop callback. Signature is: nil onKeyframe ( MOAITimer self, number keyframe, number timesExecuted, number time, number value )"
},
EVENT_TIMER_LOOP = {
type = "value",
description = "ID of event loop callback. Signature is: nil onLoop ( MOAITimer self, number timesExecuted )"
},
LOOP = {
type = "value"
},
LOOP_REVERSE = {
type = "value"
},
NORMAL = {
type = "value"
},
PING_PONG = {
type = "value"
},
REVERSE = {
type = "value"
},
getSpeed = {
type = "method",
description = "Return the playback speed.\n\n–> MOAITimer self\n<– number speed",
args = "MOAITimer self",
returns = "number speed",
valuetype = "number"
},
getTime = {
type = "method",
description = "Return the current time.\n\n–> MOAITimer self\n<– number time",
args = "MOAITimer self",
returns = "number time",
valuetype = "number"
},
getTimesExecuted = {
type = "method",
description = "Gets the number of times the timer has completed a cycle.\n\n–> MOAITimer self\n<– number nTimes",
args = "MOAITimer self",
returns = "number nTimes",
valuetype = "number"
},
setCurve = {
type = "method",
description = "Set or clear the curve to use for event generation.\n\n–> MOAITimer self\n[–> MOAIAnimCurve curve: Default value is nil.]\n<– nil",
args = "(MOAITimer self, [MOAIAnimCurve curve])",
returns = "nil"
},
setMode = {
type = "method",
description = "Sets the playback mode of the timer.\n\n–> MOAITimer self\n–> number mode: One of: MOAITimer.NORMAL, MOAITimer.REVERSE, MOAITimer.LOOP, MOAITimer.LOOP_REVERSE, MOAITimer.PING_PONG\n<– nil",
args = "(MOAITimer self, number mode)",
returns = "nil"
},
setSpan = {
type = "method",
description = "Sets the playback mode of the timer.\n\nOverload:\n–> MOAITimer self\n–> number endTime\n<– nil\n\nOverload:\n–> MOAITimer self\n–> number startTime\n–> number endTime\n<– nil",
args = "(MOAITimer self, [number startTime])",
returns = "nil"
},
setSpeed = {
type = "method",
description = "Sets the playback speed. This affects only the timer, not its children in the action tree.\n\n–> MOAITimer self\n–> number speed\n<– nil",
args = "(MOAITimer self, number speed)",
returns = "nil"
},
setTime = {
type = "method",
description = "Manually set the current time. This will be wrapped into the current span.\n\n–> MOAITimer self\n[–> number time: Default value is 0.]\n<– nil",
args = "(MOAITimer self, [number time])",
returns = "nil"
}
}
},
MOAITouchSensor = {
type = "class",
inherits = "MOAISensor",
description = "Multitouch sensor. Tracks up to 16 simultaneous touches.",
childs = {
TOUCH_CANCEL = {
type = "value"
},
TOUCH_DOWN = {
type = "value"
},
TOUCH_MOVE = {
type = "value"
},
TOUCH_UP = {
type = "value"
},
down = {
type = "method",
description = "Checks to see if the screen was touched during the last iteration.\n\n–> MOAITouchSensor self\n[–> number idx: Index of touch to check.]\n<– boolean wasPressed",
args = "(MOAITouchSensor self, [number idx])",
returns = "boolean wasPressed",
valuetype = "boolean"
},
getActiveTouches = {
type = "method",
description = "Returns the IDs of all of the touches currently occurring (for use with getTouch).\n\n–> MOAITouchSensor self\n<– number idx1\n<– ...\n<– number idxN",
args = "MOAITouchSensor self",
returns = "(number idx1, ..., number idxN)",
valuetype = "number"
},
getTouch = {
type = "method",
description = "Checks to see if there are currently touches being made on the screen.\n\n–> MOAITouchSensor self\n–> number id: The ID of the touch.\n<– number x\n<– number y\n<– number tapCount",
args = "(MOAITouchSensor self, number id)",
returns = "(number x, number y, number tapCount)",
valuetype = "number"
},
hasTouches = {
type = "method",
description = "Checks to see if there are currently touches being made on the screen.\n\n–> MOAITouchSensor self\n<– boolean hasTouches",
args = "MOAITouchSensor self",
returns = "boolean hasTouches",
valuetype = "boolean"
},
isDown = {
type = "method",
description = "Checks to see if the touch status is currently down.\n\n–> MOAITouchSensor self\n[–> number idx: Index of touch to check.]\n<– boolean isDown",
args = "(MOAITouchSensor self, [number idx])",
returns = "boolean isDown",
valuetype = "boolean"
},
setAcceptCancel = {
type = "method",
description = "Sets whether or not to accept cancel events ( these happen on iOS backgrounding ), default value is false\n\n–> MOAITouchSensor self\n–> boolean accept: true then touch cancel events will be sent\n<– nil",
args = "(MOAITouchSensor self, boolean accept)",
returns = "nil"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued when the pointer location changes.\n\n–> MOAITouchSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAITouchSensor self, [function callback])",
returns = "nil"
},
setTapMargin = {
type = "method",
description = "Sets maximum distance between two touches for them to be considered a tap\n\n–> MOAITouchSensor self\n–> number margin: Max difference on x and y between taps\n<– nil",
args = "(MOAITouchSensor self, number margin)",
returns = "nil"
},
setTapTime = {
type = "method",
description = "Sets the time between each touch for it to be counted as a tap\n\n–> MOAITouchSensor self\n–> number time: New time between taps\n<– nil",
args = "(MOAITouchSensor self, number time)",
returns = "nil"
},
up = {
type = "method",
description = "Checks to see if the screen was untouched (is no longer being touched) during the last iteration.\n\n–> MOAITouchSensor self\n[–> number idx: Index of touch to check.]\n<– boolean wasPressed",
args = "(MOAITouchSensor self, [number idx])",
returns = "boolean wasPressed",
valuetype = "boolean"
}
}
},
MOAITransform = {
type = "class",
inherits = "MOAITransformBase",
description = "Transformation hierarchy node.",
childs = {
ATTR_ROTATE_QUAT = {
type = "value"
},
ATTR_TRANSLATE = {
type = "value"
},
ATTR_X_LOC = {
type = "value"
},
ATTR_X_PIV = {
type = "value"
},
ATTR_X_ROT = {
type = "value"
},
ATTR_X_SCL = {
type = "value"
},
ATTR_Y_LOC = {
type = "value"
},
ATTR_Y_PIV = {
type = "value"
},
ATTR_Y_ROT = {
type = "value"
},
ATTR_Y_SCL = {
type = "value"
},
ATTR_Z_LOC = {
type = "value"
},
ATTR_Z_PIV = {
type = "value"
},
ATTR_Z_ROT = {
type = "value"
},
ATTR_Z_SCL = {
type = "value"
},
INHERIT_LOC = {
type = "value"
},
INHERIT_TRANSFORM = {
type = "value"
},
addLoc = {
type = "method",
description = "Adds a delta to the transform's location.\n\n–> MOAITransform self\n–> number xDelta\n–> number yDelta\n–> number zDelta\n<– nil",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta)",
returns = "nil"
},
addPiv = {
type = "method",
description = "Adds a delta to the transform's pivot.\n\n–> MOAITransform self\n–> number xDelta\n–> number yDelta\n–> number zDelta\n<– nil",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta)",
returns = "nil"
},
addRot = {
type = "method",
description = "Adds a delta to the transform's rotation\n\n–> MOAITransform self\n–> number xDelta: In degrees.\n–> number yDelta: In degrees.\n–> number zDelta: In degrees.\n<– nil",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta)",
returns = "nil"
},
addScl = {
type = "method",
description = "Adds a delta to the transform's scale\n\n–> MOAITransform self\n–> number xSclDelta\n[–> number ySclDelta: Default value is xSclDelta.]\n[–> number zSclDelta: Default value is 0.]\n<– nil",
args = "(MOAITransform self, number xSclDelta, [number ySclDelta, [number zSclDelta]])",
returns = "nil"
},
getLoc = {
type = "method",
description = "Returns the transform's current location.\n\n–> MOAITransform self\n<– number xLoc\n<– number yLoc\n<– number zLoc",
args = "MOAITransform self",
returns = "(number xLoc, number yLoc, number zLoc)",
valuetype = "number"
},
getPiv = {
type = "method",
description = "Returns the transform's current pivot.\n\n–> MOAITransform self\n<– number xPiv\n<– number yPiv\n<– number zPiv",
args = "MOAITransform self",
returns = "(number xPiv, number yPiv, number zPiv)",
valuetype = "number"
},
getRot = {
type = "method",
description = "Returns the transform's current rotation.\n\n–> MOAITransform self\n<– number xRot: Rotation in degrees.\n<– number yRot: Rotation in degrees.\n<– number zRot: Rotation in degrees.",
args = "MOAITransform self",
returns = "(number xRot, number yRot, number zRot)",
valuetype = "number"
},
getScl = {
type = "method",
description = "Returns the transform's current scale.\n\n–> MOAITransform self\n<– number xScl\n<– number yScl\n<– number zScl",
args = "MOAITransform self",
returns = "(number xScl, number yScl, number zScl)",
valuetype = "number"
},
modelToWorld = {
type = "method",
description = "Transform a point in model space to world space.\n\n–> MOAITransform self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number z: Default value is 0.]\n<– number x\n<– number y\n<– number z",
args = "(MOAITransform self, [number x, [number y, [number z]]])",
returns = "(number x, number y, number z)",
valuetype = "number"
},
move = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xDelta: Delta to be added to x.\n–> number yDelta: Delta to be added to y.\n–> number zDelta: Delta to be added to z.\n–> number xRotDelta: Delta to be added to x rot (in degrees).\n–> number yRotDelta: Delta to be added to y rot (in degrees).\n–> number zRotDelta: Delta to be added to z rot (in degrees).\n–> number xSclDelta: Delta to be added to x scale.\n–> number ySclDelta: Delta to be added to y scale.\n–> number zSclDelta: Delta to be added to z scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta, number xRotDelta, number yRotDelta, number zRotDelta, number xSclDelta, number ySclDelta, number zSclDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveLoc = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xDelta: Delta to be added to x.\n–> number yDelta: Delta to be added to y.\n–> number zDelta: Delta to be added to z.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
movePiv = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xDelta: Delta to be added to xPiv.\n–> number yDelta: Delta to be added to yPiv.\n–> number zDelta: Delta to be added to zPiv.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveRot = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xDelta: Delta to be added to xRot (in degrees).\n–> number yDelta: Delta to be added to yRot (in degrees).\n–> number zDelta: Delta to be added to zRot (in degrees).\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xDelta, number yDelta, number zDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveScl = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xSclDelta: Delta to be added to x scale.\n–> number ySclDelta: Delta to be added to y scale.\n–> number zSclDelta: Delta to be added to z scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xSclDelta, number ySclDelta, number zSclDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seek = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xGoal: Desired resulting value for x.\n–> number yGoal: Desired resulting value for y.\n–> number zGoal: Desired resulting value for z.\n–> number xRotGoal: Desired resulting value for x rot (in degrees).\n–> number yRotGoal: Desired resulting value for y rot (in degrees).\n–> number zRotGoal: Desired resulting value for z rot (in degrees).\n–> number xSclGoal: Desired resulting value for x scale.\n–> number ySclGoal: Desired resulting value for y scale.\n–> number zSclGoal: Desired resulting value for z scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xGoal, number yGoal, number zGoal, number xRotGoal, number yRotGoal, number zRotGoal, number xSclGoal, number ySclGoal, number zSclGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekLoc = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xGoal: Desired resulting value for x.\n–> number yGoal: Desired resulting value for y.\n–> number zGoal: Desired resulting value for z.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xGoal, number yGoal, number zGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekPiv = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xGoal: Desired resulting value for xPiv.\n–> number yGoal: Desired resulting value for yPiv.\n–> number zGoal: Desired resulting value for zPiv.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xGoal, number yGoal, number zGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekRot = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xRotGoal: Desired resulting value for x rot (in degrees).\n–> number yRotGoal: Desired resulting value for y rot (in degrees).\n–> number zRotGoal: Desired resulting value for z rot (in degrees).\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xRotGoal, number yRotGoal, number zRotGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekScl = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform self\n–> number xSclGoal: Desired resulting value for x scale.\n–> number ySclGoal: Desired resulting value for y scale.\n–> number zSclGoal: Desired resulting value for z scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform self, number xSclGoal, number ySclGoal, number zSclGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
setLoc = {
type = "method",
description = "Sets the transform's location.\n\n–> MOAITransform self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number z: Default value is 0.]\n<– nil",
args = "(MOAITransform self, [number x, [number y, [number z]]])",
returns = "nil"
},
setParent = {
type = "method",
description = "This method has been deprecated. Use MOAINode setAttrLink instead.\n\n–> MOAITransform self\n[–> MOAINode parent: Default value is nil.]\n<– nil",
args = "(MOAITransform self, [MOAINode parent])",
returns = "nil"
},
setPiv = {
type = "method",
description = "Sets the transform's pivot.\n\n–> MOAITransform self\n[–> number xPiv: Default value is 0.]\n[–> number yPiv: Default value is 0.]\n[–> number zPiv: Default value is 0.]\n<– nil",
args = "(MOAITransform self, [number xPiv, [number yPiv, [number zPiv]]])",
returns = "nil"
},
setRot = {
type = "method",
description = "Sets the transform's rotation.\n\n–> MOAITransform self\n[–> number xRot: Default value is 0.]\n[–> number yRot: Default value is 0.]\n[–> number zRot: Default value is 0.]\n<– nil",
args = "(MOAITransform self, [number xRot, [number yRot, [number zRot]]])",
returns = "nil"
},
setScl = {
type = "method",
description = "Sets the transform's scale.\n\n–> MOAITransform self\n–> number xScl\n[–> number yScl: Default value is xScl.]\n[–> number zScl: Default value is 1.]\n<– nil",
args = "(MOAITransform self, number xScl, [number yScl, [number zScl]])",
returns = "nil"
},
setShearByX = {
type = "method",
description = "Sets the shear for the Y and Z axes by X.\n\n–> MOAITransform self\n–> number yx: Default value is 0.\n[–> number zx: Default value is 0.]\n<– nil",
args = "(MOAITransform self, number yx, [number zx])",
returns = "nil"
},
setShearByY = {
type = "method",
description = "Sets the shear for the X and Z axes by Y.\n\n–> MOAITransform self\n–> number xy: Default value is 0.\n[–> number zy: Default value is 0.]\n<– nil",
args = "(MOAITransform self, number xy, [number zy])",
returns = "nil"
},
setShearByZ = {
type = "method",
description = "Sets the shear for the X and Y axes by Z.\n\n–> MOAITransform self\n–> number xz: Default value is 0.\n[–> number yz: Default value is 0.]\n<– nil",
args = "(MOAITransform self, number xz, [number yz])",
returns = "nil"
},
worldToModel = {
type = "method",
description = "Transform a point in world space to model space.\n\n–> MOAITransform self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n[–> number z: Default value is 0.]\n<– number x\n<– number y\n<– number z",
args = "(MOAITransform self, [number x, [number y, [number z]]])",
returns = "(number x, number y, number z)",
valuetype = "number"
}
}
},
MOAITransform2D = {
type = "class",
inherits = "MOAITransformBase",
description = "2D transformation hierarchy node.",
childs = {
ATTR_X_LOC = {
type = "value"
},
ATTR_X_PIV = {
type = "value"
},
ATTR_X_SCL = {
type = "value"
},
ATTR_Y_LOC = {
type = "value"
},
ATTR_Y_PIV = {
type = "value"
},
ATTR_Y_SCL = {
type = "value"
},
ATTR_Z_ROT = {
type = "value"
},
INHERIT_LOC = {
type = "value"
},
INHERIT_TRANSFORM = {
type = "value"
},
addLoc = {
type = "method",
description = "Adds a delta to the transform's location.\n\n–> MOAITransform2D self\n–> number xDelta\n–> number yDelta\n<– nil",
args = "(MOAITransform2D self, number xDelta, number yDelta)",
returns = "nil"
},
addPiv = {
type = "method",
description = "Adds a delta to the transform's pivot.\n\n–> MOAITransform2D self\n–> number xDelta\n–> number yDelta\n<– nil",
args = "(MOAITransform2D self, number xDelta, number yDelta)",
returns = "nil"
},
addRot = {
type = "method",
description = "Adds a delta to the transform's rotation\n\n–> MOAITransform2D self\n–> number xDelta: In degrees.\n–> number yDelta: In degrees.\n<– nil",
args = "(MOAITransform2D self, number xDelta, number yDelta)",
returns = "nil"
},
addScl = {
type = "method",
description = "Adds a delta to the transform's scale\n\n–> MOAITransform2D self\n–> number xSclDelta\n[–> number ySclDelta: Default value is xSclDelta.]\n<– nil",
args = "(MOAITransform2D self, number xSclDelta, [number ySclDelta])",
returns = "nil"
},
getLoc = {
type = "method",
description = "Returns the transform's current location.\n\n–> MOAITransform2D self\n<– number xLoc\n<– number yLoc",
args = "MOAITransform2D self",
returns = "(number xLoc, number yLoc)",
valuetype = "number"
},
getPiv = {
type = "method",
description = "Returns the transform's current pivot.\n\n–> MOAITransform2D self\n<– number xPiv\n<– number yPiv",
args = "MOAITransform2D self",
returns = "(number xPiv, number yPiv)",
valuetype = "number"
},
getRot = {
type = "method",
description = "Returns the transform's current rotation.\n\n–> MOAITransform2D self\n<– number zRot: Rotation in degrees.",
args = "MOAITransform2D self",
returns = "number zRot",
valuetype = "number"
},
getScl = {
type = "method",
description = "Returns the transform's current scale.\n\n–> MOAITransform2D self\n<– number xScl\n<– number yScl",
args = "MOAITransform2D self",
returns = "(number xScl, number yScl)",
valuetype = "number"
},
modelToWorld = {
type = "method",
description = "Transform a point in model space to world space.\n\n–> MOAITransform2D self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n<– number x\n<– number y",
args = "(MOAITransform2D self, [number x, [number y]])",
returns = "(number x, number y)",
valuetype = "number"
},
move = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xDelta: Delta to be added to x.\n–> number yDelta: Delta to be added to y.\n–> number zRotDelta: Delta to be added to z rot (in degrees).\n–> number xSclDelta: Delta to be added to x scale.\n–> number ySclDelta: Delta to be added to y scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xDelta, number yDelta, number zRotDelta, number xSclDelta, number ySclDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveLoc = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xDelta: Delta to be added to x.\n–> number yDelta: Delta to be added to y.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xDelta, number yDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
movePiv = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xDelta: Delta to be added to xPiv.\n–> number yDelta: Delta to be added to yPiv.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xDelta, number yDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveRot = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number zDelta: Delta to be added to zRot (in degrees).\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number zDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
moveScl = {
type = "method",
description = "Animate the transform by applying a delta. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xSclDelta: Delta to be added to x scale.\n–> number ySclDelta: Delta to be added to y scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xSclDelta, number ySclDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seek = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xGoal: Desired resulting value for x.\n–> number yGoal: Desired resulting value for y.\n–> number zRotGoal: Desired resulting value for z rot (in degrees).\n–> number xSclGoal: Desired resulting value for x scale.\n–> number ySclGoal: Desired resulting value for y scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xGoal, number yGoal, number zRotGoal, number xSclGoal, number ySclGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekLoc = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xGoal: Desired resulting value for x.\n–> number yGoal: Desired resulting value for y.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xGoal, number yGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekPiv = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xGoal: Desired resulting value for xPiv.\n–> number yGoal: Desired resulting value for yPiv.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xGoal, number yGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekRot = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number zRotGoal: Desired resulting value for z rot (in degrees).\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number zRotGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
seekScl = {
type = "method",
description = "Animate the transform by applying a delta. Delta is computed given a target value. Creates and returns a MOAIEaseDriver initialized to apply the delta.\n\n–> MOAITransform2D self\n–> number xSclGoal: Desired resulting value for x scale.\n–> number ySclGoal: Desired resulting value for y scale.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAITransform2D self, number xSclGoal, number ySclGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
setLoc = {
type = "method",
description = "Sets the transform's location.\n\n–> MOAITransform2D self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n<– nil",
args = "(MOAITransform2D self, [number x, [number y]])",
returns = "nil"
},
setParent = {
type = "method",
description = "This method has been deprecated. Use MOAINode setAttrLink instead.\n\n–> MOAITransform2D self\n[–> MOAINode parent: Default value is nil.]\n<– nil",
args = "(MOAITransform2D self, [MOAINode parent])",
returns = "nil"
},
setPiv = {
type = "method",
description = "Sets the transform's pivot.\n\n–> MOAITransform2D self\n[–> number xPiv: Default value is 0.]\n[–> number yPiv: Default value is 0.]\n<– nil",
args = "(MOAITransform2D self, [number xPiv, [number yPiv]])",
returns = "nil"
},
setRot = {
type = "method",
description = "Sets the transform's rotation.\n\n–> MOAITransform2D self\n[–> number zRot: Default value is 0.]\n<– nil",
args = "(MOAITransform2D self, [number zRot])",
returns = "nil"
},
setScl = {
type = "method",
description = "Sets the transform's scale.\n\n–> MOAITransform2D self\n–> number xScl\n[–> number yScl: Default value is xScl.]\n<– nil",
args = "(MOAITransform2D self, number xScl, [number yScl])",
returns = "nil"
},
worldToModel = {
type = "method",
description = "Transform a point in world space to model space.\n\n–> MOAITransform2D self\n[–> number x: Default value is 0.]\n[–> number y: Default value is 0.]\n<– number x\n<– number y",
args = "(MOAITransform2D self, [number x, [number y]])",
returns = "(number x, number y)",
valuetype = "number"
}
}
},
MOAITransformBase = {
type = "class",
inherits = "MOAINode",
description = "Base class for 2D affine transforms.",
childs = {
ATTR_WORLD_X_LOC = {
type = "value"
},
ATTR_WORLD_X_SCL = {
type = "value"
},
ATTR_WORLD_Y_LOC = {
type = "value"
},
ATTR_WORLD_Y_SCL = {
type = "value"
},
ATTR_WORLD_Z_LOC = {
type = "value"
},
ATTR_WORLD_Z_ROT = {
type = "value"
},
ATTR_WORLD_Z_SCL = {
type = "value"
},
TRANSFORM_TRAIT = {
type = "value"
},
getWorldDir = {
type = "method",
description = "Returns the normalized direction vector of the transform. This value is returned in world space so includes parent transforms (if any).\n\n–> MOAITransformBase self\n<– number xDirection\n<– number yDirection\n<– number zDirection",
args = "MOAITransformBase self",
returns = "(number xDirection, number yDirection, number zDirection)",
valuetype = "number"
},
getWorldLoc = {
type = "method",
description = "Get the transform's location in world space.\n\n–> MOAITransformBase self\n<– number xLoc\n<– number yLoc\n<– number zLoc",
args = "MOAITransformBase self",
returns = "(number xLoc, number yLoc, number zLoc)",
valuetype = "number"
},
getWorldRot = {
type = "method",
description = "Get the transform's rotation in world space.\n\n–> MOAITransformBase self\n<– number degrees",
args = "MOAITransformBase self",
returns = "number degrees",
valuetype = "number"
},
getWorldScl = {
type = "method",
description = "Get the transform's scale in world space.\n\n–> MOAITransformBase self\n<– number xScale\n<– number yScale\n<– number zScale",
args = "MOAITransformBase self",
returns = "(number xScale, number yScale, number zScale)",
valuetype = "number"
}
}
},
MOAITstoreGamecenterAndroid = {
type = "class",
inherits = "MOAILuaObject",
childs = {
authTstore = {
type = "function",
description = "Authorizes the app through Tstore\n\n–> boolean wantsLogin\n<– nil",
args = "boolean wantsLogin",
returns = "nil"
},
checkTstoreInstalled = {
type = "function",
description = "Checks if the Tstore app is installed\n\n<– boolean installed",
args = "()",
returns = "boolean installed",
valuetype = "boolean"
},
disableGamecenter = {
type = "function",
description = "Disables Tstore Gamecenter\n\n<– nil",
args = "()",
returns = "nil"
},
enableGamecenter = {
type = "function",
description = "Enables Tstore Gamecenter\n\n<– nil",
args = "()",
returns = "nil"
},
getRankList = {
type = "function",
description = "Gets the leaderboard list\n\n<– nil",
args = "()",
returns = "nil"
},
getUserInfo = {
type = "function",
description = "Gets the userinfo\n\n<– nil",
args = "()",
returns = "nil"
},
installGamecenter = {
type = "function",
description = "Installs the Tstore Gamecenter app\n\n<– nil",
args = "()",
returns = "nil"
},
installTstore = {
type = "function",
description = "Installs the Tstore app\n\n<– nil",
args = "()",
returns = "nil"
},
invokeTstoreJoinPage = {
type = "function",
description = "Invokes the Tstore join page\n\n<– nil",
args = "()",
returns = "nil"
},
openGallery = {
type = "function",
description = "opens gallery for profile pic selection\n\n<– nil",
args = "()",
returns = "nil"
},
setPoint = {
type = "function",
description = 'Records a point to the leaderboard\n\n–> string score: ( convert number to string in Lua )\n–> string pointName: ( score + "points" or score + "rubies" )\n<– nil',
args = "(string score, string pointName)",
returns = "nil"
},
setUserInfo = {
type = "function",
description = "Records a new user nickname\n\n–> string nickname\n<– nil",
args = "string nickname",
returns = "nil"
},
startGamecenter = {
type = "function",
description = "Starts the gamecenter app\n\n<– number status: Can be GAMECENTER_INSTALLED, GAMECENTER_UPGRADING, GAMECENTER_NOT_INSTALLED",
args = "()",
returns = "number status",
valuetype = "number"
}
}
},
MOAITstoreWallAndroid = {
type = "class",
inherits = "MOAILuaObject",
childs = {
showOfferWall = {
type = "function",
description = "Displays the Tstore marketplace.\n\n<– nil",
args = "()",
returns = "nil"
}
}
},
MOAITwitterAndroid = {
type = "class",
inherits = "MOAILuaObject",
description = "Wrapper for Twitter integration on Android devices. Twitter provides social integration for sharing on www.twitter.com.",
childs = {
SESSION_DID_LOGIN = {
type = "value",
description = "Event indicating a successfully completed Twitter login."
},
SESSION_DID_NOT_LOGIN = {
type = "value",
description = "Event indicating an unsuccessful (or canceled) Twitter login."
},
TWEET_CANCELLED = {
type = "value",
description = "Event indicating an unsuccessful Tweet."
},
TWEET_SUCCESSFUL = {
type = "value",
description = "Event indicating a successful Tweet.."
},
init = {
type = "function",
description = "Initialize Twitter.\n\n–> string consumerKey: OAuth consumer key\n–> string consumerSecret: OAuth consumer secret\n–> string callbackUrl: Available in Twitter developer settings.\n<– nil",
args = "(string consumerKey, string consumerSecret, string callbackUrl)",
returns = "nil"
},
isLoggedIn = {
type = "function",
description = "Determine if twitter is currently authorized.\n\n<– boolean isLoggedIn: True if logged in, false otherwise.",
args = "()",
returns = "boolean isLoggedIn",
valuetype = "boolean"
},
login = {
type = "function",
description = "Prompt the user to login to Twitter.\n\n<– nil",
args = "()",
returns = "nil"
},
sendTweet = {
type = "function",
description = "Tweet the provided text\n\n[–> string text: The text for the tweet.]\n<– nil",
args = "[string text]",
returns = "nil"
},
setAccessToken = {
type = "function",
description = "Set the access token that authenticates the user.\n\n–> string token: OAuth token\n–> string tokenSecret: OAuth token secret\n<– nil",
args = "(string token, string tokenSecret)",
returns = "nil"
}
}
},
MOAIUntzSampleBuffer = {
type = "class",
inherits = "MOAILuaObject",
description = "Uncompressed WAV data held in memory. May be shared between multiple MOAIUntzSound objects.",
childs = {
getData = {
type = "method",
description = "Retrieve every sample data in buffer\n\n–> MOAIUntzSampleBuffer self\n<– table data: Array of sample data numbers ( -1 ~ 1 as sample level)",
args = "MOAIUntzSampleBuffer self",
returns = "table data",
valuetype = "table"
},
getInfo = {
type = "method",
description = "Returns attributes of sample buffer.\n\n–> MOAIUntzSampleBuffer self\n<– number bitsPerSample\n<– number channelCount: number of channels (mono=1, stereo=2)\n<– number frameCount: number of total frames contained\n<– number sampleRate: 44100, 22050, etc.\n<– number length: sound length in seconds",
args = "MOAIUntzSampleBuffer self",
returns = "(number bitsPerSample, number channelCount, number frameCount, number sampleRate, number length)",
valuetype = "number"
},
load = {
type = "method",
description = "Loads a sound from disk.\n\n–> MOAIUntzSampleBuffer self\n–> string filename\n<– nil",
args = "(MOAIUntzSampleBuffer self, string filename)",
returns = "nil"
},
prepareBuffer = {
type = "method",
description = "Allocate internal memory for sample buffer\n\n–> MOAIUntzSampleBuffer self\n–> number channelCount: number of channels (mono=1, stereo=2)\n–> number frameCount: number of total frames of sample\n–> number sampleRate: sample rate in Hz (44100 or else)\n<– nil",
args = "(MOAIUntzSampleBuffer self, number channelCount, number frameCount, number sampleRate)",
returns = "nil"
},
setData = {
type = "method",
description = "Write sample data into buffer\n\n–> MOAIUntzSampleBuffer self\n–> table data: Array of sample data numbers ( -1 ~ 1 as sample level )\n–> number index: Index within sample buffer to start copying from (1 for the first sample)\n<– nil",
args = "(MOAIUntzSampleBuffer self, table data, number index)",
returns = "nil"
}
}
},
MOAIUntzSound = {
type = "class",
inherits = "MOAINode",
description = "Untz sound object.",
childs = {
ATTR_VOLUME = {
type = "value"
},
getFilename = {
type = "method",
description = "Return the file name of the sound.\n\n–> MOAIUntzSound self\n<– string filename",
args = "MOAIUntzSound self",
returns = "string filename",
valuetype = "string"
},
getLength = {
type = "method",
description = "Return the duration of the sound.\n\n–> MOAIUntzSound self\n<– number length",
args = "MOAIUntzSound self",
returns = "number length",
valuetype = "number"
},
getPosition = {
type = "method",
description = "Return the position of the cursor in the sound.\n\n–> MOAIUntzSound self\n<– number position",
args = "MOAIUntzSound self",
returns = "number position",
valuetype = "number"
},
getVolume = {
type = "method",
description = "Return the volume of the sound.\n\n–> MOAIUntzSound self\n<– number volume",
args = "MOAIUntzSound self",
returns = "number volume",
valuetype = "number"
},
isLooping = {
type = "method",
description = "Return the looping status if the sound.\n\n–> MOAIUntzSound self\n<– boolean looping",
args = "MOAIUntzSound self",
returns = "boolean looping",
valuetype = "boolean"
},
isPaused = {
type = "method",
description = "Return the pause status of the sound.\n\n–> MOAIUntzSound self\n<– boolean paused",
args = "MOAIUntzSound self",
returns = "boolean paused",
valuetype = "boolean"
},
isPlaying = {
type = "method",
description = "Return the playing status of the sound.\n\n–> MOAIUntzSound self\n<– boolean playing",
args = "MOAIUntzSound self",
returns = "boolean playing",
valuetype = "boolean"
},
load = {
type = "method",
description = "Loads a sound from disk or from a buffer.\n\nOverload:\n–> MOAIUntzSound self\n–> string filename\n[–> boolean loadIntoMemory: Default value is true]\n<– nil\n\nOverload:\n–> MOAIUntzSound self\n–> MOAIUntzSampleBuffer data\n<– nil",
args = "(MOAIUntzSound self, ((string filename, [boolean loadIntoMemory]) | MOAIUntzSampleBuffer data))",
returns = "nil"
},
moveVolume = {
type = "method",
description = "Animation helper for volume attribute,\n\n–> MOAIUntzSound self\n–> number vDelta: Delta to be added to v.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAIUntzSound self, number vDelta, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
pause = {
type = "method",
description = "Pause the sound.\n\n–> MOAIUntzSound self\n<– nil",
args = "MOAIUntzSound self",
returns = "nil"
},
play = {
type = "method",
description = "Play the sound.\n\n–> MOAIUntzSound self\n<– nil",
args = "MOAIUntzSound self",
returns = "nil"
},
seekVolume = {
type = "method",
description = "Animation helper for volume attribute,\n\n–> MOAIUntzSound self\n–> number vGoal: Desired resulting value for v.\n–> number length: Length of animation in seconds.\n[–> number mode: The ease mode. One of MOAIEaseType.EASE_IN, MOAIEaseType.EASE_OUT, MOAIEaseType.FLAT MOAIEaseType.LINEAR, MOAIEaseType.SMOOTH, MOAIEaseType.SOFT_EASE_IN, MOAIEaseType.SOFT_EASE_OUT, MOAIEaseType.SOFT_SMOOTH. Defaults to MOAIEaseType.SMOOTH.]\n<– MOAIEaseDriver easeDriver",
args = "(MOAIUntzSound self, number vGoal, number length, [number mode])",
returns = "MOAIEaseDriver easeDriver",
valuetype = "MOAIEaseDriver"
},
setLooping = {
type = "method",
description = "Set or clear the looping status of the sound.\n\n–> MOAIUntzSound self\n[–> boolean looping: Default value is 'false.']\n<– nil",
args = "(MOAIUntzSound self, [boolean looping])",
returns = "nil"
},
setLoopPoints = {
type = "method",
description = "Sets the start and end looping positions for the sound\n\n–> MOAIUntzSound self\n–> number startTime\n–> number endTime\n<– nil",
args = "(MOAIUntzSound self, number startTime, number endTime)",
returns = "nil"
},
setPosition = {
type = "method",
description = "Sets the position of the sound cursor.\n\n–> MOAIUntzSound self\n[–> number position: Default value is 0.]\n<– nil",
args = "(MOAIUntzSound self, [number position])",
returns = "nil"
},
setVolume = {
type = "method",
description = "Sets the volume of the sound.\n\n–> MOAIUntzSound self\n[–> number volume: Default value is 0.]\n<– nil",
args = "(MOAIUntzSound self, [number volume])",
returns = "nil"
},
stop = {
type = "method",
description = "Stops the sound from playing.\n\n–> MOAIUntzSound self\n<– nil",
args = "MOAIUntzSound self",
returns = "nil"
}
}
},
MOAIUntzSystem = {
type = "class",
inherits = "MOAILuaObject",
description = "Untz system singleton.",
childs = {
getSampleRate = {
type = "function",
description = "Return the system's current sample rate.\n\n<– number sampleRate",
args = "()",
returns = "number sampleRate",
valuetype = "number"
},
getVolume = {
type = "function",
description = "Return the system's current volume\n\n<– number volume",
args = "()",
returns = "number volume",
valuetype = "number"
},
initialize = {
type = "function",
description = "Initialize the sound system.\n\n[–> number sampleRate: Default value is 44100.]\n[–> number numFrames: Default value is 8192]\n<– nil",
args = "[number sampleRate, [number numFrames]]",
returns = "nil"
},
setSampleRate = {
type = "function",
description = "Set the system sample rate.\n\n[–> number sampleRate: Default value is 44100.]\n<– nil",
args = "[number sampleRate]",
returns = "nil"
},
setVolume = {
type = "function",
description = "Set the system level volume.\n\n[–> number volume: Valid Range: 0 >= x <= 1.0 (Default value is 1.0)]\n<– nil",
args = "[number volume]",
returns = "nil"
}
}
},
MOAIVecPathGraph = {
type = "class",
inherits = "MOAILuaObject",
childs = {
areNeighbors = {
type = "method",
description = "Checks if two nodes are neighbors.\n\n–> MOAIVecPathGraph self\n–> number nodeID1\n–> number nodeID2\n<– boolean",
args = "(MOAIVecPathGraph self, number nodeID1, number nodeID2)",
returns = "boolean",
valuetype = "boolean"
},
getNode = {
type = "method",
description = "Returns the coordinates of a node.\n\n–> MOAIVecPathGraph self\n–> number nodeID\n<– number x\n<– number y\n<– number z",
args = "(MOAIVecPathGraph self, number nodeID)",
returns = "(number x, number y, number z)",
valuetype = "number"
},
getNodeCount = {
type = "method",
description = "Returns the number of nodes in the graph.\n\n–> MOAIVecPathGraph self\n<– number count",
args = "MOAIVecPathGraph self",
returns = "number count",
valuetype = "number"
},
reserveNodes = {
type = "method",
description = "Reserves memory for a given number of nodes.\n\n–> MOAIVecPathGraph self\n–> number nNodes\n<– nil",
args = "(MOAIVecPathGraph self, number nNodes)",
returns = "nil"
},
setNeighbors = {
type = "method",
description = "Sets the neighborhood relation for two nodes.\n\n–> MOAIVecPathGraph self\n–> number nodeID1\n–> number nodeID2\n[–> boolean value: Whether the nodes are neighbors (true) or not (false). Defaults to true.]\n<– nil",
args = "(MOAIVecPathGraph self, number nodeID1, number nodeID2, [boolean value])",
returns = "nil"
},
setNode = {
type = "method",
description = "Sets the coordinates of a node.\n\n–> MOAIVecPathGraph self\n–> number nodeID\n[–> number x: Defaults to 0.]\n[–> number y: Defaults to 0.]\n[–> number z: Defaults to 0.]\n<– nil",
args = "(MOAIVecPathGraph self, number nodeID, [number x, [number y, [number z]]])",
returns = "nil"
}
}
},
MOAIVertexBuffer = {
type = "class",
inherits = "MOAILuaObject",
description = "Vertex buffer class.",
childs = {
bless = {
type = "method",
description = "Call this after initializing the buffer and settings it vertices to prepare it for use.\n\n–> MOAIVertexBuffer self\n<– nil",
args = "MOAIVertexBuffer self",
returns = "nil"
},
release = {
type = "method",
description = "Releases any memory associated with buffer.\n\n–> MOAIVertexBuffer self\n<– nil",
args = "MOAIVertexBuffer self",
returns = "nil"
},
reserve = {
type = "method",
description = "Sets capacity of buffer in bytes.\n\n–> MOAIVertexBuffer self\n–> number size\n<– nil",
args = "(MOAIVertexBuffer self, number size)",
returns = "nil"
},
reserveVerts = {
type = "method",
description = "Sets capacity of buffer in vertices. This function should only be used after attaching a valid MOAIVertexFormat to the buffer.\n\n–> MOAIVertexBuffer self\n–> number size\n<– nil",
args = "(MOAIVertexBuffer self, number size)",
returns = "nil"
},
reset = {
type = "method",
description = "Resets the vertex stream writing to the head of the stream.\n\n–> MOAIVertexBuffer self\n<– nil",
args = "MOAIVertexBuffer self",
returns = "nil"
},
setFormat = {
type = "method",
description = "Sets the vertex format for the buffer.\n\n–> MOAIVertexBuffer self\n–> MOAIVertexFormat format\n<– nil",
args = "(MOAIVertexBuffer self, MOAIVertexFormat format)",
returns = "nil"
},
writeColor32 = {
type = "method",
description = "Write a packed 32-bit color to the vertex buffer.\n\n–> MOAIVertexBuffer self\n[–> number r: Default value is 1.]\n[–> number g: Default value is 1.]\n[–> number b: Default value is 1.]\n[–> number a: Default value is 1.]\n<– nil",
args = "(MOAIVertexBuffer self, [number r, [number g, [number b, [number a]]]])",
returns = "nil"
},
writeFloat = {
type = "method",
description = "Write a 32-bit float to the vertex buffer.\n\n–> MOAIVertexBuffer self\n[–> number f: Default value is 0.]\n<– nil",
args = "(MOAIVertexBuffer self, [number f])",
returns = "nil"
},
writeInt16 = {
type = "method",
description = "Write an 16-bit integer to the vertex buffer.\n\n–> MOAIVertexBuffer self\n[–> number i: Default value is 0.]\n<– nil",
args = "(MOAIVertexBuffer self, [number i])",
returns = "nil"
},
writeInt32 = {
type = "method",
description = "Write an 32-bit integer to the vertex buffer.\n\n–> MOAIVertexBuffer self\n[–> number i: Default value is 0.]\n<– nil",
args = "(MOAIVertexBuffer self, [number i])",
returns = "nil"
},
writeInt8 = {
type = "method",
description = "Write an 8-bit integer to the vertex buffer.\n\n–> MOAIVertexBuffer self\n[–> number i: Default value is 0.]\n<– nil",
args = "(MOAIVertexBuffer self, [number i])",
returns = "nil"
}
}
},
MOAIVertexFormat = {
type = "class",
inherits = "MOAILuaObject",
description = "Vertex format class.",
childs = {
declareAttribute = {
type = "method",
description = "Declare a custom attribute (for use with programmable pipeline).\n\n–> MOAIVertexFormat self\n–> number index: Default value is 1.\n–> number type: Data type of component elements. See OpenGL ES documentation.\n–> number size: Number of elements. See OpenGL ES documentation.\n[–> boolean normalized: See OpenGL ES documentation.]\n<– nil",
args = "(MOAIVertexFormat self, number index, number type, number size, [boolean normalized])",
returns = "nil"
},
declareColor = {
type = "method",
description = "Declare a vertex color.\n\n–> MOAIVertexFormat self\n–> number index\n–> number type: Data type of component elements. See OpenGL ES documentation.\n<– nil",
args = "(MOAIVertexFormat self, number index, number type)",
returns = "nil"
},
declareCoord = {
type = "method",
description = "Declare a vertex coordinate.\n\n–> MOAIVertexFormat self\n–> number index\n–> number type: Data type of coordinate elements. See OpenGL ES documentation.\n–> number size: Number of coordinate elements. See OpenGL ES documentation.\n<– nil",
args = "(MOAIVertexFormat self, number index, number type, number size)",
returns = "nil"
},
declareNormal = {
type = "method",
description = "Declare a vertex normal.\n\n–> MOAIVertexFormat self\n–> number index\n–> number type: Data type of normal elements. See OpenGL ES documentation.\n<– nil",
args = "(MOAIVertexFormat self, number index, number type)",
returns = "nil"
},
declareUV = {
type = "method",
description = "Declare a vertex texture coordinate.\n\n–> MOAIVertexFormat self\n–> number index\n–> number type: Data type of texture coordinate elements. See OpenGL ES documentation.\n–> number size: Number of texture coordinate elements. See OpenGL ES documentation.\n<– nil",
args = "(MOAIVertexFormat self, number index, number type, number size)",
returns = "nil"
}
}
},
MOAIViewport = {
type = "class",
inherits = "MOAILuaObject ZLRect",
description = "Viewport object.",
childs = {
setOffset = {
type = "method",
description = "Sets the viewport offset in normalized view space (size of viewport is -1 to 1 in both directions).\n\n–> MOAIViewport self\n–> number xOff\n–> number yOff\n<– nil",
args = "(MOAIViewport self, number xOff, number yOff)",
returns = "nil"
},
setRotation = {
type = "method",
description = "Sets global rotation to be added to camera transform.\n\n–> MOAIViewport self\n–> number rotation\n<– nil",
args = "(MOAIViewport self, number rotation)",
returns = "nil"
},
setScale = {
type = "method",
description = "Sets the number of world units visible of the viewport for one or both dimensions. Set 0 for one of the dimensions to use a derived value based on the other dimension and the aspect ratio. Negative values are also OK. It is typical to set the scale to the number of pixels visible in the this-> This practice is neither endorsed nor condemned. Note that the while the contents of the viewport will appear to stretch or shrink to match the dimensions of the viewport given by setSize, the number of world units visible will remain constant.\n\n–> MOAIViewport self\n–> number xScale\n–> number yScale\n<– nil",
args = "(MOAIViewport self, number xScale, number yScale)",
returns = "nil"
},
setSize = {
type = "method",
description = "Sets the dimensions of the this->\n\nOverload:\n–> MOAIViewport self\n–> number width\n–> number height\n<– nil\n\nOverload:\n–> MOAIViewport self\n–> number left\n–> number top\n–> number right\n–> number bottom\n<– nil",
args = "(MOAIViewport self, ((number width, number height) | (number left, number top, number right, number bottom)))",
returns = "nil"
}
}
},
MOAIWebViewIOS = {
type = "class",
inherits = "MOAIInstanceEventSource",
description = "Wrapper for UIWebView interaction on iOS devices.",
childs = {
DID_FAIL_LOAD_WITH_ERROR = {
type = "value",
description = "Event indicating a failed UIWebView load."
},
NAVIGATION_BACK_FORWARD = {
type = "value",
description = "Indicates the the navigation was due to a back/forward operation."
},
NAVIGATION_FORM_RESUBMIT = {
type = "value",
description = "Indicates the the navigation was due to a form resubmit."
},
NAVIGATION_FORM_SUBMIT = {
type = "value",
description = "Indicates the the navigation was due to a form submit."
},
NAVIGATION_LINK_CLICKED = {
type = "value",
description = "Indicates the the navigation was due to a link click."
},
NAVIGATION_OTHER = {
type = "value",
description = "Indicates the the navigation was due to other reasons."
},
NAVIGATION_RELOAD = {
type = "value",
description = "Indicates the the navigation was due to a page reload."
},
SHOULD_START_LOAD_WITH_REQUEST = {
type = "value",
description = "Event indicating an attempt to load a UIWebView."
},
WEB_VIEW_DID_FINISH_LOAD = {
type = "value",
description = "Event indicating a completed UIWebView load."
},
WEB_VIEW_DID_START_LOAD = {
type = "value",
description = "Event indicating the start of a UIWebView load."
}
}
},
MOAIWheelSensor = {
type = "class",
inherits = "MOAISensor",
description = "Hardware wheel sensor.",
childs = {
getDelta = {
type = "method",
description = "Returns the delta of the wheel\n\n–> MOAIWheelSensor self\n<– number delta",
args = "MOAIWheelSensor self",
returns = "number delta",
valuetype = "number"
},
getValue = {
type = "method",
description = "Returns the current value of the wheel, based on delta events\n\n–> MOAIWheelSensor self\n<– number value",
args = "MOAIWheelSensor self",
returns = "number value",
valuetype = "number"
},
setCallback = {
type = "method",
description = "Sets or clears the callback to be issued on a wheel delta event\n\n–> MOAIWheelSensor self\n[–> function callback: Default value is nil.]\n<– nil",
args = "(MOAIWheelSensor self, [function callback])",
returns = "nil"
}
}
},
MOAIXmlParser = {
type = "class",
inherits = "MOAILuaObject",
description = "Converts XML DOM to Lua trees. Provided as a convenience; not advised for parsing very large XML documents. (Use of XML not advised at all - use JSON or Lua.)",
childs = {
parseFile = {
type = "method",
description = "Parses the contents of the specified file as XML.\n\n–> MOAIXmlParser self\n–> string filename: The path of the file to read the XML data from.\n<– table data: A tree of tables representing the XML.",
args = "(MOAIXmlParser self, string filename)",
returns = "table data",
valuetype = "table"
},
parseString = {
type = "method",
description = "Parses the contents of the specified string as XML.\n\n–> MOAIXmlParser self\n–> string filename: The XML data stored in a string.\n<– table data: A tree of tables representing the XML.",
args = "(MOAIXmlParser self, string filename)",
returns = "table data",
valuetype = "table"
}
}
},
ZLColorVec = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
},
ZLRect = {
type = "class",
inherits = "MOAILuaObject",
childs = {}
}
} | gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/map/static_layouts/skeleton_construction.lua | 1 | 4030 | return {
version = "1.1",
luaversion = "5.1",
orientation = "orthogonal",
width = 12,
height = 12,
tilewidth = 16,
tileheight = 16,
properties = {},
tilesets = {
{
name = "tiles",
firstgid = 1,
tilewidth = 64,
tileheight = 64,
spacing = 0,
margin = 0,
image = "../../../../tools/tiled/dont_starve/tiles.png",
imagewidth = 512,
imageheight = 128,
properties = {},
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "BG_TILES",
x = 0,
y = 0,
width = 12,
height = 12,
visible = true,
opacity = 1,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "objectgroup",
name = "FG_OBJECTS",
visible = true,
opacity = 1,
properties = {},
objects = {
{
name = "",
type = "skeleton",
shape = "rectangle",
x = 125,
y = 130,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "footballhat",
shape = "rectangle",
x = 43,
y = 129,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "hammer",
shape = "rectangle",
x = 134,
y = 80,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "boards",
shape = "rectangle",
x = 32,
y = 96,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "boards",
shape = "rectangle",
x = 144,
y = 176,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "boards",
shape = "rectangle",
x = 73,
y = 16,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "cutstone",
shape = "rectangle",
x = 148,
y = 39,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "cutstone",
shape = "rectangle",
x = 95,
y = 79,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rope",
shape = "rectangle",
x = 80,
y = 146,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rope",
shape = "rectangle",
x = 82,
y = 111,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "blueprint",
shape = "rectangle",
x = 63,
y = 63,
width = 0,
height = 0,
visible = true,
properties = {
["data.recipetouse"] = "birdcage"
}
}
}
}
}
}
| gpl-2.0 |
unusualcrow/redead_reloaded | entities/weapons/rad_g3/shared.lua | 1 | 1428 | if SERVER then
AddCSLuaFile("shared.lua")
end
if CLIENT then
SWEP.ViewModelFlip = true
SWEP.PrintName = "G3 SG1"
SWEP.IconLetter = "i"
SWEP.Slot = 4
SWEP.Slotpos = 3
end
SWEP.HoldType = "ar2"
SWEP.Base = "rad_base"
SWEP.ViewModel = "models/weapons/v_snip_g3sg1.mdl"
SWEP.WorldModel = "models/weapons/w_snip_g3sg1.mdl"
SWEP.SprintPos = Vector(-2.8398, -3.656, 0.5519)
SWEP.SprintAng = Vector(0.1447, -34.0929, 0)
SWEP.ZoomModes = {0, 35, 10}
SWEP.ZoomSpeeds = {0.25, 0.40, 0.40}
SWEP.IsSniper = true
SWEP.AmmoType = "Sniper"
SWEP.Primary.Sound = Sound("Weapon_G3SG1.Single")
SWEP.Primary.Recoil = 5.5
SWEP.Primary.Damage = 100
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.002
SWEP.Primary.SniperCone = 0.035
SWEP.Primary.Delay = 0.380
SWEP.Primary.ClipSize = 20
SWEP.Primary.Automatic = true
function SWEP:PrimaryAttack()
if not self:CanPrimaryAttack() then
self:SetNextPrimaryFire(CurTime() + 0.25)
return
end
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
self:EmitSound(self.Primary.Sound, 100, math.random(95, 105))
self:SetClip1(self:Clip1() - 1)
self:ShootEffects()
if self.IsSniper and self:GetZoomMode() == 1 then
self:ShootBullets(self.Primary.Damage, self.Primary.NumShots, self.Primary.SniperCone, 1)
else
self:ShootBullets(self.Primary.Damage, self.Primary.NumShots, self.Primary.Cone, self:GetZoomMode())
end
if SERVER then
self.Owner:AddAmmo(self.AmmoType, -1)
end
end
| mit |
czfshine/Don-t-Starve | ZeroBraneStudio/src/editor/autocomplete.lua | 1 | 19592 | -- Copyright 2011-15 Paul Kulchenko, ZeroBrane LLC
-- authors: Luxinia Dev (Eike Decker & Christoph Kubisch)
---------------------------------------------------------
local ide = ide
local statusBar = ide.frame.statusBar
local q = EscapeMagic
-- api loading depends on Lua interpreter
-- and loaded specs
------------
-- API
local function newAPI(api)
api = api or {}
for i in pairs(api) do
api[i] = nil
end
-- tool tip info and reserved names
api.tip = {
staticnames = {},
keys = {},
finfo = {},
finfoclass = {},
shortfinfo = {},
shortfinfoclass = {},
}
-- autocomplete hierarchy
api.ac = {
childs = {},
}
return api
end
local apis = {
none = newAPI(),
lua = newAPI(),
}
function GetApi(apitype) return apis[apitype] or apis.none end
----------
-- API loading
local function gennames(tab, prefix)
for i,v in pairs(tab) do
v.classname = (prefix and (prefix..".") or "")..i
if (v.childs) then
gennames(v.childs,v.classname)
end
end
end
local function addAPI(ftype, fname) -- relative to API directory
local env = apis[ftype] or newAPI()
local res
local api = ide.apis[ftype][fname]
if type(api) == 'table' then
res = api
else
local fn, err = loadfile(api)
if err then
DisplayOutputLn(TR("Error while loading API file: %s"):format(err))
return
end
local suc
suc, res = pcall(function() return fn(env.ac.childs) end)
if (not suc) then
DisplayOutputLn(TR("Error while processing API file: %s"):format(res))
return
end
-- cache the result
ide.apis[ftype][fname] = res
end
apis[ftype] = env
gennames(res)
for i,v in pairs(res) do env.ac.childs[i] = v end
end
local function loadallAPIs(only, subapis, known)
for ftype, v in pairs(only and {[only] = ide.apis[only]} or ide.apis) do
if (not known or known[ftype]) then
for fname in pairs(v) do
if (not subapis or subapis[fname]) then addAPI(ftype, fname) end
end
end
end
end
local function scanAPIs()
for _, file in ipairs(FileSysGetRecursive("api", true, "*.lua")) do
if not IsDirectory(file) then
local ftype, fname = file:match("api[/\\]([^/\\]+)[/\\](.*)%.")
if not ftype or not fname then
DisplayOutputLn(TR("The API file must be located in a subdirectory of the API directory."))
return
end
ide.apis[ftype] = ide.apis[ftype] or {}
ide.apis[ftype][fname] = file
end
end
end
---------
-- ToolTip and reserved words list
-- also fixes function descriptions
local function fillTips(api,apibasename)
local apiac = api.ac
local tclass = api.tip
tclass.staticnames = {}
tclass.keys = {}
tclass.finfo = {}
tclass.finfoclass = {}
tclass.shortfinfo = {}
tclass.shortfinfoclass = {}
local staticnames = tclass.staticnames
local keys = tclass.keys
local finfo = tclass.finfo
local finfoclass = tclass.finfoclass
local shortfinfo = tclass.shortfinfo
local shortfinfoclass = tclass.shortfinfoclass
local function traverse (tab, libname, format)
if not tab.childs then return end
format = tab.format or format
for key,info in pairs(tab.childs) do
local fullkey = (libname ~= "" and libname.."." or "")..key
traverse(info, fullkey, format)
if info.type == "function" or info.type == "method" or info.type == "value" then
local frontname = (info.returns or "(?)").." "..fullkey.." "..(info.args or "(?)")
frontname = frontname:gsub("\n"," "):gsub("\t","")
local description = info.description or ""
-- build info
local inf = ((info.type == "value" and "" or frontname.."\n")
..description)
local sentence = description:match("^(.-)%. ?\n")
local infshort = ((info.type == "value" and "" or frontname.."\n")
..(sentence and sentence.."..." or description))
if type(format) == 'function' then -- apply custom formatting if requested
inf = format(fullkey, info, inf)
infshort = format(fullkey, info, infshort)
end
local infshortbatch = (info.returns and info.args) and frontname or infshort
-- add to infoclass
if not finfoclass[libname] then finfoclass[libname] = {} end
if not shortfinfoclass[libname] then shortfinfoclass[libname] = {} end
finfoclass[libname][key] = inf
shortfinfoclass[libname][key] = infshort
-- add to info
if not finfo[key] or #finfo[key]<200 then
if finfo[key] then finfo[key] = finfo[key] .. "\n\n"
else finfo[key] = "" end
finfo[key] = finfo[key] .. inf
elseif not finfo[key]:match("\n %(%.%.%.%)$") then
finfo[key] = finfo[key].."\n (...)"
end
-- add to shortinfo
if not shortfinfo[key] or #shortfinfo[key]<200 then
if shortfinfo[key] then shortfinfo[key] = shortfinfo[key] .. "\n"
else shortfinfo[key] = "" end
shortfinfo[key] = shortfinfo[key] .. infshortbatch
elseif not shortfinfo[key]:match("\n %(%.%.%.%)$") then
shortfinfo[key] = shortfinfo[key].."\n (...)"
end
end
if info.type == "keyword" then
keys[key] = true
end
staticnames[key] = true
end
end
traverse(apiac,apibasename)
end
local function generateAPIInfo(only)
for i,api in pairs(apis) do
if ((not only) or i == only) then
fillTips(api,"")
end
end
end
local function updateAssignCache(editor)
if (editor.spec.typeassigns and not editor.assignscache) then
local assigns = editor.spec.typeassigns(editor)
editor.assignscache = {
assigns = assigns,
line = editor:GetCurrentLine(),
}
end
end
-- assumes a tidied up string (no spaces, braces..)
local function resolveAssign(editor,tx)
local ac = editor.api.ac
local sep = editor.spec.sep
local anysep = "["..q(sep).."]"
local assigns = editor.assignscache and editor.assignscache.assigns
local function getclass(tab,a)
local key,rest = a:match("([%w_]+)"..anysep.."(.*)")
key = tonumber(key) or key -- make this work for childs[0]
if (key and rest and tab.childs and tab.childs[key]) then
return getclass(tab.childs[key],rest)
end
-- process valuetype, but only if it doesn't reference the current tab
if (tab.valuetype and tab ~= ac.childs[tab.valuetype]) then
return getclass(ac,tab.valuetype..sep:sub(1,1)..a)
end
return tab,a
end
local c
if (assigns) then
-- find assign
local change, n, stopat = true, 0, os.clock() + 0.2
while (change) do
-- abort the check if the auto-complete is taking too long
if n > 50 and os.clock() > stopat then
if ide.config.acandtip.warning then
DisplayOutputLn("Warning: Auto-complete was aborted after taking too long to complete."
.. " Please report this warning along with the text you were typing to support@zerobrane.com.")
end
break
else
n = n + 1
end
local classname = nil
c = ""
change = false
for w,s in tx:gmatch("([%w_]+)("..anysep.."?)") do
local old = classname
-- check if what we have so far can be matched with a class name
-- this can happen if it's a reference to a value with a known type
classname = classname or assigns[c..w]
if (s ~= "" and old ~= classname) then
-- continue checking unless this can lead to recursive substitution
change = not classname:find("^"..w) and not classname:find("^"..c..w)
c = classname..s
else
c = c..w..s
end
end
tx = c
-- if there is any class duplication, abort the loop
if classname and select(2, c:gsub(classname, classname)) > 1 then break end
end
else
c = tx
end
-- then work from api
return getclass(ac,c)
end
function GetTipInfo(editor, content, short, fullmatch)
if not content then return end
updateAssignCache(editor)
-- try to resolve the class
content = content:gsub("%b[]",".0")
local tab = resolveAssign(editor, content)
local sep = editor.spec.sep
local anysep = "["..q(sep).."]"
local caller = content:match("([%w_]+)%(?%s*$")
local class = (tab and tab.classname
or caller and content:match("([%w_]+)"..anysep..caller.."%(?%s*$") or "")
local tip = editor.api.tip
local classtab = short and tip.shortfinfoclass or tip.finfoclass
local funcstab = short and tip.shortfinfo or tip.finfo
if (editor.assignscache and not (class and classtab[class])) then
local assigns = editor.assignscache.assigns
class = assigns and assigns[class] or class
end
local res = (caller and (class and classtab[class]) and classtab[class][caller]
or (not fullmatch and funcstab[caller] or nil))
-- some values may not have descriptions (for example, true/false);
-- don't return empty strings as they are displayed as empty tooltips.
return res and #res > 0 and res or nil
end
local function reloadAPI(only,subapis)
newAPI(apis[only])
loadallAPIs(only,subapis)
generateAPIInfo(only)
end
function ReloadLuaAPI()
local interp = ide.interpreter
local cfgapi = ide.config.api
local fname = interp and interp.fname
local intapi = cfgapi and fname and cfgapi[fname]
local apinames = {}
-- general APIs as configured
for _, v in ipairs(type(cfgapi) == 'table' and cfgapi or {}) do apinames[v] = true end
-- interpreter-specific APIs as configured
for _, v in ipairs(type(intapi) == 'table' and intapi or {}) do apinames[v] = true end
-- interpreter APIs
for _, v in ipairs(interp and interp.api or {}) do apinames[v] = true end
reloadAPI("lua",apinames)
end
do
local known = {}
for _, spec in pairs(ide.specs) do
if (spec.apitype) then
known[spec.apitype] = true
end
end
-- by defaul load every known api except lua
known.lua = false
scanAPIs()
loadallAPIs(nil,nil,known)
generateAPIInfo()
end
-------------
-- Dynamic Words
local dywordentries = {}
local dynamicwords = {}
local function addDynamicWord (api,word)
if api.tip.keys[word] or api.tip.staticnames[word] then return end
local cnt = dywordentries[word]
if cnt then
dywordentries[word] = cnt + 1
return
end
dywordentries[word] = 1
local wlow = word:lower()
for i=0,#word do
local k = wlow:sub(1,i)
dynamicwords[k] = dynamicwords[k] or {}
table.insert(dynamicwords[k], word)
end
end
local function removeDynamicWord (api,word)
if api.tip.keys[word] or api.tip.staticnames[word] then return end
local cnt = dywordentries[word]
if not cnt then return end
if (cnt == 1) then
dywordentries[word] = nil
for i=0,#word do
local wlow = word:lower()
local k = wlow : sub (1,i)
local page = dynamicwords[k]
if page then
local cnt = #page
for n=1,cnt do
if page[n] == word then
if cnt == 1 then
dynamicwords[k] = nil
else
table.remove(page,n)
end
break
end
end
end
end
else
dywordentries[word] = cnt - 1
end
end
function DynamicWordsReset ()
dywordentries = {}
dynamicwords = {}
end
local function getEditorLines(editor,line,numlines)
return editor:GetTextRange(
editor:PositionFromLine(line),editor:PositionFromLine(line+numlines+1))
end
function DynamicWordsAdd(editor,content,line,numlines)
if ide.config.acandtip.nodynwords then return end
local api = editor.api
local anysep = "["..q(editor.spec.sep).."]"
content = content or getEditorLines(editor,line,numlines)
for word in content:gmatch(anysep.."?%s*([a-zA-Z_]+[a-zA-Z_0-9]+)") do
addDynamicWord(api,word)
end
end
function DynamicWordsRem(editor,content,line,numlines)
if ide.config.acandtip.nodynwords then return end
local api = editor.api
local anysep = "["..q(editor.spec.sep).."]"
content = content or getEditorLines(editor,line,numlines)
for word in content:gmatch(anysep.."?%s*([a-zA-Z_]+[a-zA-Z_0-9]+)") do
removeDynamicWord(api,word)
end
end
function DynamicWordsRemoveAll(editor)
DynamicWordsRem(editor,editor:GetText())
end
------------
-- Final Autocomplete
local cachemain = {}
local cachemethod = {}
local laststrategy
local function getAutoCompApiList(childs,fragment,method)
fragment = fragment:lower()
local strategy = ide.config.acandtip.strategy
if (laststrategy ~= strategy) then
cachemain = {}
cachemethod = {}
laststrategy = strategy
end
local cache = method and cachemethod or cachemain
if (strategy == 2) then
local wlist = cache[childs]
if not wlist then
wlist = " "
for i,v in pairs(childs) do
-- in some cases (tip.finfo), v may be a string; check for that first.
-- if a:b typed, then value (type == "value") not allowed
-- if a.b typed, then method (type == "method") not allowed
if type(v) ~= 'table' or (v.type and
((method and v.type ~= "value")
or (not method and v.type ~= "method"))) then
wlist = wlist..i.." "
end
end
cache[childs] = wlist
end
local ret = {}
local g = string.gmatch
local pat = fragment ~= "" and ("%s("..fragment:gsub(".",
function(c)
local l = c:lower()..c:upper()
return "["..l.."][%w_]*"
end)..")") or "([%w_]+)"
pat = pat:gsub("%s","")
for c in g(wlist,pat) do
table.insert(ret,c)
end
return ret
end
if cache[childs] and cache[childs][fragment] then
return cache[childs][fragment]
end
local t = {}
cache[childs] = t
local sub = strategy == 1
for key,v in pairs(childs) do
-- in some cases (tip.finfo), v may be a string; check for that first.
-- if a:b typed, then value (type == "value") not allowed
-- if a.b typed, then method (type == "method") not allowed
if type(v) ~= 'table' or (v.type and
((method and v.type ~= "value")
or (not method and v.type ~= "method"))) then
local used = {}
local kl = key:lower()
for i=0,#key do
local k = kl:sub(1,i)
t[k] = t[k] or {}
used[k] = true
table.insert(t[k],key)
end
if (sub) then
-- find camel case / _ separated subwords
-- glfwGetGammaRamp -> g, gg, ggr
-- GL_POINT_SPRIT -> g, gp, gps
local last = ""
for ks in string.gmatch(key,"([A-Z%d]*[a-z%d]*_?)") do
local k = last..(ks:sub(1,1):lower())
last = k
t[k] = t[k] or {}
if (not used[k]) then
used[k] = true
table.insert(t[k],key)
end
end
end
end
end
return t
end
function CreateAutoCompList(editor,key,pos)
local api = editor.api
local tip = api.tip
local ac = api.ac
local sep = editor.spec.sep
local method = key:match(":[^"..q(sep).."]*$") ~= nil
-- ignore keywords
if tip.keys[key] then return end
updateAssignCache(editor)
local tab,rest = resolveAssign(editor,key)
local progress = tab and tab.childs
statusBar:SetStatusText(progress and tab.classname or "",1)
if not (progress) then return end
if (tab == ac) then
local _, krest = rest:match("([%w_]+)["..q(sep).."]([%w_]*)%s*$")
if (krest) then
tab = #krest >= (ide.config.acandtip.startat or 2) and tip.finfo or {}
rest = krest:gsub("[^%w_]","")
else
rest = rest:gsub("[^%w_]","")
end
else
rest = rest:gsub("[^%w_]","")
end
local last = key:match("([%w_]+)%s*$")
-- build dynamic word list
-- only if api search couldnt descend
-- ie we couldnt find matching sub items
local dw = ""
if (last and #last >= (ide.config.acandtip.startat or 2)) then
last = last:lower()
if dynamicwords[last] then
local list = dynamicwords[last]
table.sort(list,function(a,b)
local ma,mb = a:sub(1,#last)==last, b:sub(1,#last)==last
if (ma and mb) or (not ma and not mb) then return a<b end
return ma
end)
-- ignore if word == last and sole user
for i,v in ipairs(list) do
if (v:lower() == last and dywordentries[v] == 1) then
table.remove(list,i)
break
end
end
dw = table.concat(list," ")
end
end
-- list from api
local apilist = getAutoCompApiList(tab.childs or tab,rest,method)
local function addInheritance(tab, apilist, seen)
if not tab.inherits then return end
for base in tab.inherits:gmatch("[%w_"..q(sep).."]+") do
local tab = ac
-- map "a.b.c" to class hierarchy (a.b.c)
for class in base:gmatch("[%w_]+") do tab = tab.childs[class] end
if tab and not seen[tab] then
seen[tab] = true
for _,v in pairs(getAutoCompApiList(tab.childs,rest,method)) do
table.insert(apilist, v)
end
addInheritance(tab, apilist, seen)
end
end
end
-- handle (multiple) inheritance; add matches from the parent class/lib
addInheritance(tab, apilist, {[tab] = true})
-- include local/global variables
if ide.config.acandtip.symbols and not key:find(q(sep)) then
local vars, context = {}
local tokens = editor:GetTokenList()
for _, token in ipairs(tokens) do
if token.fpos and pos and token.fpos > pos then break end
if token[1] == 'Id' or token[1] == 'Var' then
local var = token.name
if var ~= key and var:find(key, 1, true) == 1 then
-- if it's a global variable, store in the auto-complete list,
-- but if it's local, store separately as it needs to be checked
table.insert(token.context[var] and vars or apilist, var)
end
context = token.context
end
end
for _, var in pairs(context and vars or {}) do
if context[var] then table.insert(apilist, var) end
end
end
local compstr = ""
if apilist then
if (#rest > 0) then
local strategy = ide.config.acandtip.strategy
if (strategy == 2 and #apilist < 128) then
-- when matching "ret": "ret." < "re.t" < "r.et"
local pat = rest:gsub(".", function(c) return "["..c:lower()..c:upper().."](.-)" end)
local weights = {}
local penalty = 0.1
local function weight(str)
if not weights[str] then
local w = 0
str:gsub(pat,function(...)
local l = {...}
-- penalize gaps between matches, more so at the beginning
for n, v in ipairs(l) do w = w + #v * (1 + (#l-n)*penalty) end
end)
weights[str] = w
end
return weights[str]
end
table.sort(apilist,function(a,b)
local ma, mb = weight(a), weight(b)
if (ma == mb) then return a:lower()<b:lower() end
return ma<mb
end)
else
table.sort(apilist,function(a,b)
local ma,mb = a:sub(1,#rest)==rest, b:sub(1,#rest)==rest
if (ma and mb) or (not ma and not mb) then return a<b end
return ma
end)
end
else
table.sort(apilist)
end
local prev = apilist[#apilist]
for i = #apilist-1,1,-1 do
if prev == apilist[i] then
table.remove(apilist, i+1)
else prev = apilist[i] end
end
compstr = table.concat(apilist," ")
end
-- concat final, list complete first
local li = compstr .. (#compstr > 0 and #dw > 0 and " " or "") .. dw
return li ~= "" and (#li > 1024 and li:sub(1,1024).."..." or li) or nil
end
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/map/static_layouts/maxwell_6.lua | 1 | 6280 | return {
version = "1.1",
luaversion = "5.1",
orientation = "orthogonal",
width = 36,
height = 36,
tilewidth = 16,
tileheight = 16,
properties = {},
tilesets = {
{
name = "tiles",
firstgid = 1,
tilewidth = 64,
tileheight = 64,
spacing = 0,
margin = 0,
image = "../../../../tools/tiled/dont_starve/tiles.png",
imagewidth = 512,
imageheight = 128,
properties = {},
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "BG_TILES",
x = 0,
y = 0,
width = 36,
height = 36,
visible = true,
opacity = 1,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 10, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "objectgroup",
name = "FG_OBJECTS",
visible = true,
opacity = 1,
properties = {},
objects = {
{
name = "",
type = "marbletree",
shape = "rectangle",
x = 160,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "marbletree",
shape = "rectangle",
x = 224,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "marbletree",
shape = "rectangle",
x = 288,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "marbletree",
shape = "rectangle",
x = 352,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "marbletree",
shape = "rectangle",
x = 416,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
}
}
}
}
}
| gpl-2.0 |
liamgh/liamgreenhughes-sl4a-tf101 | lua/json4lua/json/json.lua | 20 | 15751 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.20
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local math = require('math')
local string = require("string")
local table = require("table")
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
module("json")
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.eE", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.eE"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
| apache-2.0 |
vmcraft/RemotePrinter | 3rdparty/thrift-0.9.2/lib/lua/TSocket.lua | 113 | 2996 | ---- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'TTransport'
require 'libluasocket'
-- TSocketBase
TSocketBase = TTransportBase:new{
__type = 'TSocketBase',
timeout = 1000,
host = 'localhost',
port = 9090,
handle
}
function TSocketBase:close()
if self.handle then
self.handle:destroy()
self.handle = nil
end
end
-- Returns a table with the fields host and port
function TSocketBase:getSocketInfo()
if self.handle then
return self.handle:getsockinfo()
end
terror(TTransportException:new{errorCode = TTransportException.NOT_OPEN})
end
function TSocketBase:setTimeout(timeout)
if timeout and ttype(timeout) == 'number' then
if self.handle then
self.handle:settimeout(timeout)
end
self.timeout = timeout
end
end
-- TSocket
TSocket = TSocketBase:new{
__type = 'TSocket',
host = 'localhost',
port = 9090
}
function TSocket:isOpen()
if self.handle then
return true
end
return false
end
function TSocket:open()
if self.handle then
self:close()
end
-- Create local handle
local sock, err = luasocket.create_and_connect(
self.host, self.port, self.timeout)
if err == nil then
self.handle = sock
end
if err then
terror(TTransportException:new{
message = 'Could not connect to ' .. self.host .. ':' .. self.port
.. ' (' .. err .. ')'
})
end
end
function TSocket:read(len)
local buf = self.handle:receive(self.handle, len)
if not buf or string.len(buf) ~= len then
terror(TTransportException:new{errorCode = TTransportException.UNKNOWN})
end
return buf
end
function TSocket:write(buf)
self.handle:send(self.handle, buf)
end
function TSocket:flush()
end
-- TServerSocket
TServerSocket = TSocketBase:new{
__type = 'TServerSocket',
host = 'localhost',
port = 9090
}
function TServerSocket:listen()
if self.handle then
self:close()
end
local sock, err = luasocket.create(self.host, self.port)
if not err then
self.handle = sock
else
terror(err)
end
self.handle:settimeout(self.timeout)
self.handle:listen()
end
function TServerSocket:accept()
local client, err = self.handle:accept()
if err then
terror(err)
end
return TSocket:new({handle = client})
end
| apache-2.0 |
vadrak/ArenaLive | PlayerButton.lua | 1 | 1871 | local addonName, L = ...;
ArenaLivePlayerButton = {};
local PlayerButton = ArenaLivePlayerButton;
local onDragStart, onClick; -- private functions
--[[**
* Initializes the player button btn.
*
* btn (Button) reference to an UI button that is going to be
* initialized as a player button.
]]
function PlayerButton.init(btn)
btn:RegisterForClicks("LeftButtonUp");
btn:RegisterForDrag("LeftButton");
btn:SetScript("OnDragStart", onDragStart);
btn:SetScript("OnClick", onClick);
end
--[[**
* Changes the appearance of btn according to the player data in
* pInfo, or hiding it, if playerInfo is nil.
*
* @param btn (PlayerButton) the player button which's player data
* is going to be set.
* @param pInfo (table) a single player data entry from the war
* game menu's PLAYER_LIST table.
* @see WarGameMenu.lua
]]
function PlayerButton.setPlayer(btn, pInfo)
btn.bTag = pInfo.bTag;
btn.name:SetText(pInfo.name);
btn.info:SetText(pInfo.text);
btn.icon:SetTexture(pInfo.texture);
if (pInfo.online) then
btn.bg:SetColorTexture(0, 0.694, 0.941, 0.05);
else
btn.bg:SetColorTexture(0.5, 0.5, 0.5, 0.05);
end
btn:Show();
end
--[[**
* Resets the player button btn's player data, removing all texts,
* textures and hiding it.
*
* @param btn (PlayerButton) the player button object that is going
* to be reset.
]]
function PlayerButton.reset(btn)
btn.bTag = nil;
btn.name:SetText("");
btn.info:SetText("");
btn.icon:SetTexture();
btn:Hide();
end
--[[**
* OnDragStart script callback.
*
* @param button (string) mouse button that was used to click this
* player button.
]]
onDragStart = function (btn)
ArenaLiveWarGameMenu:setCursorData(btn.bTag);
end
onClick = function(btn, mouseButton, down)
if (ArenaLiveWarGameMenu:getCursorData()) then
ArenaLiveWarGameMenu:setCursorData(nil);
end
end
| mit |
CrazyEddieTK/Zero-K | LuaUI/Configs/nubtron_config.lua | 5 | 8962 | --[[
INSTRUCTIONS
Choose names for the unitClass table and use those names in conditions.
For example if you use "Con" then you must use "ConSelected" not "conSelected":
local unitClasses = {
Con = { 'cloakcon' },
}
local steps = {
selectCon = {
image = unitClasses.Con[1] ..'.png',
passIfAny = { 'ConSelected' },
},
}
Use the mClasses table to indicate mobile units, as opposed to structures.
local mClasses = { Con=1, }
** Tasks and Steps **
Tasks and steps can either pass (move to next task/step) or fail (go to previous task/step).
A task contains a set of steps. Define the steps in a task using the "states" table (sorry, steps = states).
A task will pass when its own conditions pass and it's on its final step (state).
You can set conditions for a tasks/steps using the following tables.
** Condition tables **
errIfAny - task/step fails if any conditions are true
errIfAnyNot - task/step fails if any conditions are false
passIfAny - task/step completes if any conditions are true
passIfAnyNot - task/step completes if any conditions are false
** Generic conditions **
have<unitClass> - unit exists and is completed
<unitClass>Selected - unit is selected
** Special Built-in conditions **
clickedNubtron - user clicks Next button
commSelected - user selects commander (based on customparam in ZK)
gameStarted
guardFac - constructor (Con) guards factory (BotLab)
lowMetalIncome
lowEnergryIncome
metalMapView
** Generic Steps (autogenerated for you) **
selectBuild<unitClass> - Tells user to select a structure from the build menu
start<unitClass> - Triggers if user selected the structure to be built. Tells user to place the structure
build<unitClass> - Unit (mobile or structure) is being built
finish<unitClass> - Triggers if structure partly completed structure is no longer being built, tells user that structure needs finishing
]]
--- unit classes ---
local unitClasses = {
Mex = { 'staticmex' },
Solar = { 'energysolar' },
LLT = { 'turretlaser' },
BotLab = { 'factorycloak' },
Radar = { 'staticradar' },
Con = { 'cloakcon' },
Raider = { 'cloakraid' },
}
local unitClassNames = {
Mex = 'Mex',
Solar = 'Solar Collector',
LLT = 'LLT',
BotLab = 'Bot Lab',
Radar = 'Radar',
Con = 'Constructor',
Raider = 'Raider',
}
--mobile units
local mClasses = { Con=1, Raider=1, }
-- generic sub states
local steps = {
intro = {
--message = 'Hello! I am Nubtron, the friendly robot. I will teach you how to play Complete Annihilation. <(Click here to continue)>',
passIfAny = { 'clickedNubtron', },
},
intro2 = {
--message = 'Just follow my instructions. You can drag this window around by my face. <(Click here to continue)>',
passIfAny = { 'clickedNubtron'},
},
intro3 = {
--message = 'Practice zooming the camera in and out with your mouse\'s scroll wheel <(Click here to continue)>',
passIfAny = { 'clickedNubtron' },
},
intro4 = {
--message = 'Practice panning the camera up, down, left and right with your arrow keys. <(Click here to continue)>',
passIfAny = { 'clickedNubtron' },
},
intro5 = {
--message = 'Place your starting position by clicking on a nice flat spot on the map, then click on the <Ready> button',
passIfAny = { 'gameStarted' },
},
selectComm = {
--message = 'Select only your commander by clicking on it or pressing <ctrl+c>.',
passIfAny = {'commSelected'}
},
showMetalMap = {
--message = 'View the metal map by pressing <F4>.',
passIfAny = { 'metalMapView' }
},
hideMetalMap = {
--message = 'Hide the metal map by pressing <F4>.',
passIfAnyNot = { 'metalMapView' }
},
selectBotLab = {
--message = 'Select only your Bot Lab by clicking on it (the blue circles will help you find it).',
passIfAny = { 'BotLabSelected' }
},
selectCon = {
--message = 'Select one constructor by clicking on it (the blue circles will help you find it).',
--image = { arm='unitpics/'.. unitClasses.Con[1] ..'.png', core='unitpics/'.. unitClasses.Con[2] ..'.png' },
image = unitClasses.Con[1] ..'.png',
passIfAny = { 'ConSelected' },
},
guardFac = {
--message = 'Have the constructor guard your Bot Lab by right clicking on the Lab. The constructor will assist it until you give it a different order.',
errIfAnyNot = { 'ConSelected' },
},
--[[
rotate = {
--message = 'Try rotating.',
errIfAnyNot = { 'commSelected', 'BotLabBuildSelected' },
passIfAny = { 'clickedNubtron' }
},
--]]
tutorialEnd = {
--message = 'This is the end of the tutorial. It is now safe to shut off Nubtron. Goodbye! (Click here to restart tutorial)',
passIfAny = {'clickedNubtron'}
},
}
-- main states
-- use any names you wish here, so long as they match up to the tasks table
local taskOrder = {
'intro',
'restoreInterface',
'buildMex',
'buildSolar',
'buildLLT',
'buildMex2',
'buildSolar2',
'buildFac',
'buildRadar',
'buildCon',
'conAssist',
'buildRaider',
'congrats',
}
--use "states" from the steps table above.
local tasks = {
intro = {
--desc = 'Introduction',
states = {'intro', 'intro2', 'intro3', 'intro4', 'intro5', },
},
restoreInterface = {
--desc = 'Restore your interface',
states = { 'hideMetalMap', },
},
buildMex = {
--desc = 'Building a Metal Extractor (mex)',
--tip = 'Metal extractors output metal which is the heart of your economy.',
states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap' },
passIfAll = { 'haveMex',},
},
buildSolar = {
--desc = 'Building a Solar Collector',
--tip = 'Energy generating structures power your mexes and factories.',
states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar'},
errIfAny = { 'metalMapView' },
errIfAnyNot = { 'haveMex' },
passIfAll = { 'haveSolar',},
},
buildLLT = {
--desc = 'Building a Light Laser Tower (LLT)',
states = { 'selectComm', 'finishLLT', 'selectBuildLLT', 'startLLT', 'buildLLT' },
errIfAny = { 'metalMapView' },
errIfAnyNot = { 'haveMex', 'haveSolar' },
passIfAll = { 'haveLLT',},
},
buildMex2 = {
--desc = 'Building another mex on a different metal spot.',
---tip = 'Always try to acquire more metal spots to build more mexes.',
states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap'},
errIfAnyNot = { 'haveMex', 'haveSolar' },
passIfAnyNot = { 'lowMetalIncome', },
},
buildSolar2 = {
--desc = 'Building another Solar Collector',
--tip = 'Always try and build more energy structures to keep your economy growing.',
states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar', },
errIfAny = { 'metalMapView', },
errIfAnyNot = { 'haveMex', 'haveSolar' },
passIfAnyNot = { 'lowEnergyIncome', }
},
buildFac = {
--desc = 'Building a Factory',
states = { 'selectComm', 'finishBotLab', 'selectBuildBotLab', 'startBotLab', 'buildBotLab' },
errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', },
errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT' },
passIfAll = { 'haveBotLab',},
},
buildRadar = {
--desc = 'Building a Radar',
--tip = 'Radar coverage shows you distant enemy units as blips.',
states = { 'selectComm', 'finishRadar', 'selectBuildRadar', 'startRadar', 'buildRadar' },
errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', },
errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab' },
passIfAll = { 'haveRadar',},
},
buildCon = {
--desc = 'Building a Constructor',
--tip = 'Just like your Commander, Constructors build (and assist building of) structures.',
states = { 'selectBotLab', 'selectBuildCon', 'buildCon' },
errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', },
errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar' },
passIfAll = { 'haveCon',},
},
conAssist = {
--desc = 'Using a constructor to assist your factory',
--tip = 'Factories that are assisted by constructors build faster.',
states = { 'selectCon', 'guardFac', },
errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', },
errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon' },
passIfAll = { 'guardFac',},
},
buildRaider = {
--desc = 'Building Raider Bots in your factory.',
--tip = 'Combat units are used to attack your enemies and make them suffer.',
states = { 'selectBotLab', 'selectBuildRaider', 'buildRaider', },
errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', },
errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon', 'guardFac' },
passIfAll = { 'haveRaider',},
},
congrats = {
--desc = 'Congratulations!',
errIfAny = { 'metalMapView' },
states = { 'tutorialEnd'},
},
}
return {unitClasses=unitClasses, unitClassNames=unitClassNames, mClasses=mClasses, steps=steps, tasks=tasks, taskOrder=taskOrder,} | gpl-2.0 |
czfshine/Don-t-Starve | mods/Cretaceous/wicker/utils/time.lua | 6 | 1831 | --[[
Copyright (C) 2013 simplex
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
local _G = _G
---
local factored_time_meta = {
__tostring = function(t)
if t.d > 0 then
return ("%dd%02dh%02dm%02ds"):format(t.d, t.h, t.m, t.s)
end
if t.h > 0 then
return ("%dh%02dm%02ds"):format(t.h, t.m, t.s)
end
if t.m > 0 then
return ("%dm%02ds"):format(t.m, t.s)
end
return ("%ds"):format(t.s)
end
}
-- Factors and rounds time (given in seconds) into hours, minutes and seconds.
function FactorTime(dt)
local s, m, h, d
s = math.floor(dt)
m = math.floor(s*(1/60))
s = s % 60
h = math.floor(m*(1/60))
m = m % 60
d = math.floor(h*(1/24))
h = h % 24
return setmetatable(
{d = d, h = h, m = m, s = s},
factored_time_meta
)
end
Factor = FactorTime
local function basic_time_formatter(fmt)
return function()
return os.date(fmt)
end
end
if IsWorldgen() then
TimeFormatter = basic_time_formatter
else
local FMT_TICK_THRESHOLD = 15
function TimeFormatter(fmt)
local get_str = basic_time_formatter(fmt)
local next_tick = -math.huge
local str = nil
return function()
local tick = _G.GetTick()
if tick >= next_tick then
str = get_str()
next_tick = tick + FMT_TICK_THRESHOLD
end
return str
end
end
end
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/forest.lua | 1 | 2881 | local assets =
{
Asset("IMAGE", "images/colour_cubes/day05_cc.tex"),
Asset("IMAGE", "images/colour_cubes/dusk03_cc.tex"),
Asset("IMAGE", "images/colour_cubes/night03_cc.tex"),
Asset("IMAGE", "images/colour_cubes/snow_cc.tex"),
Asset("IMAGE", "images/colour_cubes/snowdusk_cc.tex"),
Asset("IMAGE", "images/colour_cubes/night04_cc.tex"),
Asset("IMAGE", "images/colour_cubes/insane_day_cc.tex"),
Asset("IMAGE", "images/colour_cubes/insane_dusk_cc.tex"),
Asset("IMAGE", "images/colour_cubes/insane_night_cc.tex"),
Asset("ANIM", "anim/snow.zip"),
Asset("ANIM", "anim/lightning.zip"),
Asset("ANIM", "anim/splash_ocean.zip"),
Asset("ANIM", "anim/frozen.zip"),
Asset("SOUND", "sound/forest_stream.fsb"),
Asset("IMAGE", "levels/textures/snow.tex"),
Asset("IMAGE", "images/wave.tex"),
}
local forest_prefabs =
{
"world",
"adventure_portal",
"resurrectionstone",
"deerclops",
"gravestone",
"flower",
"animal_track",
"dirtpile",
"beefaloherd",
"beefalo",
"penguinherd",
"penguin_ice",
"penguin",
"koalefant_summer",
"koalefant_winter",
"beehive",
"wasphive",
"walrus_camp",
"pighead",
"mermhead",
"rabbithole",
"carrot_planted",
"tentacle",
"wormhole",
"cave_entrance",
"teleportato_base",
"teleportato_ring",
"teleportato_box",
"teleportato_crank",
"teleportato_potato",
"pond",
"marsh_tree",
"marsh_bush",
"reeds",
"mist",
"snow",
"rain",
"maxwellthrone",
"maxwellendgame",
"maxwelllight",
"maxwelllock",
"maxwellphonograph",
"puppet_wilson",
"puppet_willow",
"puppet_wendy",
"puppet_wickerbottom",
"puppet_wolfgang",
"puppet_wx78",
"puppet_wes",
"marblepillar",
"marbletree",
"statueharp",
"statuemaxwell",
"eyeplant",
"lureplant",
"purpleamulet",
"monkey",
"livingtree",
}
local function fn(Sim)
local inst = SpawnPrefab("world")
inst.prefab = "forest"
inst.entity:SetCanSleep(false)
--add waves
local waves = inst.entity:AddWaveComponent()
waves:SetRegionSize( 40, 20 )
waves:SetRegionNumWaves( 8 )
waves:SetWaveTexture( "images/wave.tex" )
-- See source\game\components\WaveRegion.h
waves:SetWaveEffect( "shaders/waves.ksh" ) -- texture.ksh
--waves:SetWaveEffect( "shaders/texture.ksh" ) --
waves:SetWaveSize( 2048, 512 )
inst:AddComponent("clock")
inst:AddComponent("seasonmanager")
inst:AddComponent("birdspawner")
inst:AddComponent("butterflyspawner")
inst:AddComponent("hounded")
inst:AddComponent("basehassler")
inst:AddComponent("hunter")
inst.components.butterflyspawner:SetButterfly("butterfly")
inst:AddComponent("frograin")
inst:AddComponent("lureplantspawner")
inst:AddComponent("penguinspawner")
inst:AddComponent("colourcubemanager")
inst.Map:SetOverlayTexture( "levels/textures/snow.tex" )
return inst
end
return Prefab( "forest", fn, assets, forest_prefabs)
| gpl-2.0 |
DipColor/ajab3 | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
starkos/premake-core | modules/vstudio/tests/vc200x/test_project_refs.lua | 16 | 1831 | --
-- tests/actions/vstudio/vc200x/test_project_refs.lua
-- Validate project references in Visual Studio 200x C/C++ projects.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vstudio_vs200x_project_refs")
local vc200x = p.vstudio.vc200x
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2008")
wks = test.createWorkspace()
uuid "00112233-4455-6677-8888-99AABBCCDDEE"
test.createproject(wks)
end
local function prepare(platform)
prj = test.getproject(wks, 2)
vc200x.projectReferences(prj)
end
--
-- If there are no sibling projects listed in links(), then the
-- entire project references item group should be skipped.
--
function suite.noProjectReferencesGroup_onNoSiblingReferences()
prepare()
test.isemptycapture()
end
--
-- If a sibling project is listed in links(), an item group should
-- be written with a reference to that sibling project.
--
function suite.projectReferenceAdded_onSiblingProjectLink()
links { "MyProject" }
prepare()
test.capture [[
<ProjectReference
ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}"
RelativePathToProject=".\MyProject.vcproj"
/>
]]
end
--
-- Project references should always be specified relative to the
-- *solution* doing the referencing. Which is kind of weird, since it
-- would be incorrect if the project were included in more than one
-- solution file, yes?
--
function suite.referencesAreRelative_onDifferentProjectLocation()
links { "MyProject" }
location "build/MyProject2"
project("MyProject")
location "build/MyProject"
prepare()
test.capture [[
<ProjectReference
ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}"
RelativePathToProject=".\build\MyProject\MyProject.vcproj"
/>
]]
end
| bsd-3-clause |
CrazyEddieTK/Zero-K | LuaUI/Widgets/unit_cloakfirestate2.lua | 5 | 3429 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Cloak Fire State 2",
desc = "Sets units to Hold Fire when cloaked, reverts to original state when decloaked",
author = "KingRaptor (L.J. Lim)",
date = "Feb 14, 2010",
license = "GNU GPL, v2 or later",
layer = -1,
enabled = true -- loaded by default?
}
end
local enabled = true
local function CheckEnable()
if Spring.GetSpectatingState() or (not options.enable_cloak_holdfire.value) then
enabled = false
else
enabled = true
end
end
options_path = 'Settings/Unit Behaviour'
options_order = {'enable_cloak_holdfire'}
options = {
enable_cloak_holdfire = {
name = "Hold fire when cloaked",
type = 'bool',
value = false,
noHotkey = true,
desc = 'Units which cloak will hold fire so as not to reveal themselves.',
OnChange = CheckEnable,
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Speedups
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetUnitStates = Spring.GetUnitStates
local GetUnitDefID = Spring.GetUnitDefID
local GetUnitIsCloaked = Spring.GetUnitIsCloaked
local STATIC_STATE_TABLE = {0}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local myTeam
local exceptionList = { --add exempt units here
"cloaksnipe",
"cloakaa",
"wolverine_mine",
"gunshipbomb",
}
local exceptionArray = {}
for _,name in pairs(exceptionList) do
local ud = UnitDefNames[name]
if ud then
exceptionArray[ud.id] = true
end
end
local cloakUnit = {} --stores the desired fire state when decloaked of each unitID
function widget:UnitCloaked(unitID, unitDefID, teamID)
if (not enabled) or (teamID ~= myTeam) or exceptionArray[unitDefID] then
return
end
local states = GetUnitStates(unitID)
cloakUnit[unitID] = states.firestate --store last state
if states.firestate ~= 0 then
STATIC_STATE_TABLE[1] = 0
GiveOrderToUnit(unitID, CMD.FIRE_STATE, STATIC_STATE_TABLE, 0)
end
end
function widget:UnitDecloaked(unitID, unitDefID, teamID)
if (not enabled) or (teamID ~= myTeam) or exceptionArray[unitDefID] or (not cloakUnit[unitID]) then
return
end
local states = GetUnitStates(unitID)
if states.firestate == 0 then
local targetState = cloakUnit[unitID]
STATIC_STATE_TABLE[1] = targetState
GiveOrderToUnit(unitID, CMD.FIRE_STATE, STATIC_STATE_TABLE, 0) --revert to last state
--Spring.Echo("Unit compromised - weapons free!")
end
cloakUnit[unitID] = nil
end
function widget:PlayerChanged()
myTeam = Spring.GetMyTeamID()
CheckEnable()
end
function widget:Initialize()
myTeam = Spring.GetMyTeamID()
CheckEnable()
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (not enabled) then
return
end
if unitTeam == myTeam then
local states = GetUnitStates(unitID)
cloakUnit[unitID] = states.firestate
else
cloakUnit[unitID] = nil
end
end
function widget:UnitGiven(unitID, unitDefID, unitTeam)
widget:UnitCreated(unitID, unitDefID, unitTeam)
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
if cloakUnit[unitID] then
cloakUnit[unitID] = nil
end
end
| gpl-2.0 |
minetest-games/Minetest_TNG | mods/default/lua/nodes/ores.lua | 2 | 7246 | -- mods/default/lua/nodes/ores.lua
-- ===============================
-- See README.txt for licensing and other information.
-- Minerals
local stones = {
{"stone"},
{"sandstone"},
{"desert_stone"}
}
for _,stone in pairs(stones) do
stone = stone[1]
default.register_node("default:" .. stone .. "_with_coal", {
description = "Coal Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_coal.png"},
groups = {cracky = 3, not_in_creative_inventory = 1},
drop = 'default:coal_lump',
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:" .. stone .. "_with_iron", {
description = "Iron Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_iron.png"},
groups = {cracky = 2, not_in_creative_inventory = 1},
drop = 'default:iron_lump',
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:" .. stone .. "_with_copper", {
description = "Copper Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_copper.png"},
groups = {cracky = 2, not_in_creative_inventory = 1},
drop = 'default:copper_lump',
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:" .. stone .. "_with_mese", {
description = "Mese Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_mese.png"},
paramtype = "light",
groups = {cracky = 1, not_in_creative_inventory = 1},
drop = "default:mese_crystal",
sounds = default.node_sound_stone_defaults(),
light_source = 1,
})
default.register_node("default:" .. stone .. "_with_diamond", {
description = "Diamond Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_diamond.png"},
groups = {cracky = 1, not_in_creative_inventory = 1},
drop = "default:diamond",
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:" .. stone .. "_with_gold", {
description = "Gold Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_gold.png"},
drop = "default:gold_lump",
groups = {cracky = 2, not_in_creative_inventory = 1},
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:" .. stone .. "_with_salt", {
description = "Salt Ore",
tiles = {"default_" .. stone .. ".png^default_mineral_salt.png"},
groups = {cracky = 2, not_in_creative_inventory = 1},
drop = {
max_items = 5,
items = {
{items = {"default:salt 2"}},
{items = {"default:salt"}, rarity = 2},
{items = {"default:salt"}, rarity = 3},
{items = {"default:salt"}, rarity = 5}
}
},
sounds = default.node_sound_stone_defaults(),
})
end
-- Blocks
default.register_node("default:mese", {
description = "Mese Block",
tiles = {"default_mese_block.png"},
paramtype = "light",
groups = {cracky = 1, level = 2},
sounds = default.node_sound_stone_defaults(),
light_source = 3,
})
default.register_node("default:coalblock", {
register = {stair = true, slab = true},
description = "Coal Block",
tiles = {"default_coal_block.png"},
is_ground_content = false,
groups = {cracky = 3, fuel = 370},
sounds = default.node_sound_stone_defaults(),
})
default.register_node("default:steelblock", {
register = {stair = true, slab = true},
description = "Steel Block",
tiles = {"default_steel_block.png"},
is_ground_content = false,
groups = {cracky = 1, level = 2},
sounds = default.node_sound_stone_defaults(),
stair = {legacy_alias = "stairs:stair_steelblock"},
slab = {legacy_alias = "stairs:slab_steelblock"},
})
default.register_node("default:copperblock", {
register = {stair = true, slab = true},
description = "Copper Block",
tiles = {"default_copper_block.png"},
is_ground_content = false,
groups = {cracky = 1, level = 2},
sounds = default.node_sound_stone_defaults(),
stair = {legacy_alias = "stairs:stair_copperblock"},
slab = {legacy_alias = "stairs:slab_copperblock"},
})
default.register_node("default:bronzeblock", {
register = {stair = true, slab = true},
description = "Bronze Block",
tiles = {"default_bronze_block.png"},
is_ground_content = false,
groups = {cracky = 1, level = 2},
sounds = default.node_sound_stone_defaults(),
stair = {legacy_alias = "stairs:stair_bronzeblock"},
slab = {legacy_alias = "stairs:slab_bronzeblock"},
})
default.register_node("default:goldblock", {
register = {stair = true, slab = true},
description = "Gold Block",
tiles = {"default_gold_block.png"},
is_ground_content = false,
groups = {cracky = 1},
sounds = default.node_sound_stone_defaults(),
stair = {legacy_alias = "stairs:stair_goldblock"},
slab = {legacy_alias = "stairs:slab_goldblock"},
})
default.register_node("default:diamondblock", {
register = {stair = true, slab = true},
description = "Diamond Block",
tiles = {"default_diamond_block.png"},
is_ground_content = false,
groups = {cracky = 1, level = 3},
sounds = default.node_sound_stone_defaults(),
stair = {legacy_alias = "stairs:stair_diamondblock"},
slab = {legacy_alias = "stairs:slab_diamondblock"},
})
default.register_node("default:saltblock", {
register = {stair = true, slab = true},
description = "Salt Block",
tiles = {"default_salt_block.png"},
is_ground_content = false,
groups = {cracky = 2},
sounds = default.node_sound_stone_defaults(),
})
--
-- Crafting
--
core.register_craft({
output = "default:mese",
recipe = {
{"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"},
{"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"},
{"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"},
}
})
core.register_craft({
output = "default:coalblock",
recipe = {
{"default:coal_lump", "default:coal_lump", "default:coal_lump"},
{"default:coal_lump", "default:coal_lump", "default:coal_lump"},
{"default:coal_lump", "default:coal_lump", "default:coal_lump"},
}
})
core.register_craft({
output = "default:steelblock",
recipe = {
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
}
})
core.register_craft({
output = "default:copperblock",
recipe = {
{"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"},
{"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"},
{"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"},
}
})
core.register_craft({
output = "default:bronzeblock",
recipe = {
{"default:bronze_ingot", "default:bronze_ingot", "default:bronze_ingot"},
{"default:bronze_ingot", "default:bronze_ingot", "default:bronze_ingot"},
{"default:bronze_ingot", "default:bronze_ingot", "default:bronze_ingot"},
}
})
core.register_craft({
output = "default:goldblock",
recipe = {
{"default:gold_ingot", "default:gold_ingot", "default:gold_ingot"},
{"default:gold_ingot", "default:gold_ingot", "default:gold_ingot"},
{"default:gold_ingot", "default:gold_ingot", "default:gold_ingot"},
}
})
core.register_craft({
output = "default:diamondblock",
recipe = {
{"default:diamond", "default:diamond", "default:diamond"},
{"default:diamond", "default:diamond", "default:diamond"},
{"default:diamond", "default:diamond", "default:diamond"},
}
})
| gpl-3.0 |
victorperin/tibia-server | data/npc/scripts/Palomino.lua | 1 | 3295 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local Aluguel_mounts = {
["brown rented horse"] = {price = 500, days = 1, mountid = 22, level = 10, premium = false, storage = 50561},
["grey rented horse"] = {price = 500, days = 1, mountid = 25, level = 10, premium = false, storage = 50562}
}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if msgcontains(msg, "transport") then
npcHandler:say("We can bring you to Venore with one of our coaches for 125 gold. Are you interested?", cid)
npcHandler.topic[cid] = 5
elseif(msgcontains(msg, 'yes') and npcHandler.topic[cid] == 5) then
if player:getMoney() >= 125 then
player:removeMoney(125)
npcHandler:say("Have a nice trip!", cid)
local port = {x = 32850, y = 32124, z = 7}
player:teleportTo(port)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
npcHandler.topic[cid] = 0
else
npcHandler:say("You don't have enough money.", cid)
end
end
local msg = string.lower(msg)
if isInArray({"rent", "mounts", "mount", "horses"}, msg) then
selfSay("You can buy {brown rented horse} and {grey rented horse}!", cid)
npcHandler.topic[cid] = 1
elseif npcHandler.topic[cid] == 1 then
if Aluguel_mounts[msg] then
if Aluguel_mounts[msg].premium == true and not isPremium(cid) then
selfSay('You need to be premium to rent this mount.', cid) return true
elseif player:getLevel() < Aluguel_mounts[msg].level then
selfSay('You need level ' .. Aluguel_mounts[msg].level .. ' or more to rent this mount.', cid) return true
elseif player:getStorageValue(Aluguel_mounts[msg].storage) >= os.time() then
selfSay('you already have rented this mount!', cid) return true
end
name, price, stor, days, mountid = msg, Aluguel_mounts[msg].price, Aluguel_mounts[msg].storage, Aluguel_mounts[msg].days, Aluguel_mounts[msg].mountid
selfSay('Do you want to '..name..' for '..days..' day'..(days > 1 and 's' or '')..' the price '..price..' gps?', cid)
npcHandler.topic[cid] = 2
else
selfSay('Sorry, I do not rent this mount.', cid)
end
elseif(msgcontains(msg, 'yes') and npcHandler.topic[cid] == 2) then
if player:removeMoney(price) then
player:addMount(mountid)
player:setStorageValue(stor, os.time()+days*86400)
selfSay('Here is your '..name..', it will last until '..os.date("%d %B %Y %X", player:getStorageValue(stor))..'.', cid)
else
selfSay('You do not have enough money to rent the mount!', cid)
npcHandler.topic[cid] = 0
end
elseif msgcontains(msg, "no") then
selfSay("Then not", cid)
npcHandler.topic[cid] = 0
npcHandler:releaseFocus(cid)
npcHandler:resetNpc(cid)
end
return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| apache-2.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/plant_normal.lua | 1 | 1453 | local assets =
{
Asset("ANIM", "anim/plant_normal.zip"),
-- products for buildswap
Asset("ANIM", "anim/durian.zip"),
Asset("ANIM", "anim/eggplant.zip"),
Asset("ANIM", "anim/dragonfruit.zip"),
Asset("ANIM", "anim/pomegranate.zip"),
Asset("ANIM", "anim/corn.zip"),
Asset("ANIM", "anim/pumpkin.zip"),
Asset("ANIM", "anim/carrot.zip"),
}
require "prefabs/veggies"
local prefabs = {}
for k,v in pairs(VEGGIES) do
table.insert(prefabs, k)
end
local function onmatured(inst)
inst.SoundEmitter:PlaySound("dontstarve/common/farm_harvestable")
inst.AnimState:OverrideSymbol("swap_grown", inst.components.crop.product_prefab,inst.components.crop.product_prefab.."01")
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
anim:SetBank("plant_normal")
anim:SetBuild("plant_normal")
anim:PlayAnimation("grow")
inst:AddComponent("crop")
inst.components.crop:SetOnMatureFn(onmatured)
inst:AddComponent("inspectable")
inst.components.inspectable.getstatus = function(inst)
if inst.components.crop:IsReadyForHarvest() then
return "READY"
else
return "GROWING"
end
end
anim:SetFinalOffset(-1)
return inst
end
return Prefab( "common/objects/plant_normal", fn, assets, prefabs)
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Configs/StartBoxes/Melt_V2.lua | 17 | 2902 | return {
[0] = {
startpoints = {
{6796, 3900},
{6828, 6819},
{6729, 976},
{6744, 5419},
{7393, 2418},
},
boxes = {
{
{6375, 3672},
{6226, 3864},
{6262, 4098},
{6163, 4157},
{6202, 4308},
{6364, 4360},
{6379, 4361},
{6551, 4322},
{6764, 4428},
{6775, 4426},
{6936, 4223},
{7203, 4207},
{7378, 3934},
{7316, 3650},
{7067, 3393},
{6777, 3195},
{6528, 3451},
{6506, 3475},
},
{
{6345, 6508},
{6219, 6651},
{6316, 6912},
{6411, 7171},
{6678, 7376},
{6977, 7373},
{6993, 7373},
{7239, 7271},
{7242, 7261},
{7287, 6926},
{7533, 6791},
{7485, 6401},
{6915, 6116},
{6747, 6192},
{6765, 6356},
{6743, 6351},
{6610, 6336},
{6388, 6180},
},
{
{6170, 899},
{6172, 920},
{6231, 1140},
{6355, 1202},
{6497, 1375},
{6679, 1431},
{6998, 1421},
{7277, 1273},
{7244, 1094},
{7328, 864},
{7283, 591},
{6963, 449},
{6468, 234},
{6326, 507},
{6176, 690},
},
{
{6595, 5176},
{6580, 5186},
{6492, 5348},
{6499, 5362},
{6591, 5467},
{6514, 5655},
{6669, 5761},
{6945, 5598},
{7050, 5323},
{6890, 5059},
{6794, 5064},
},
{
{7077, 2366},
{7077, 2378},
{7218, 2639},
{7357, 2715},
{7486, 2582},
{7623, 2188},
{7351, 2111},
{7212, 2262},
},
},
nameLong = "East",
nameShort = "E",
},
[1] = {
startpoints = {
{1237, 3926},
{1767, 6588},
{1225, 1201},
{1815, 5265},
{1069, 2539},
},
boxes = {
{
{677, 3856},
{708, 4147},
{970, 4268},
{930, 4462},
{1079, 4528},
{1290, 4439},
{1507, 4590},
{1615, 4254},
{2025, 3932},
{2140, 3869},
{1882, 3513},
{1415, 3154},
{958, 3272},
{772, 3547},
{670, 3659},
},
{
{1068, 6557},
{1107, 6956},
{1353, 6985},
{1629, 7174},
{1641, 7177},
{1662, 7177},
{2165, 7041},
{2179, 6879},
{2415, 6713},
{2413, 6683},
{2351, 6373},
{2256, 6075},
{2242, 6075},
{2219, 6076},
{1875, 6023},
{1858, 6011},
{1649, 5861},
{1418, 6093},
{1210, 6291},
},
{
{522, 1246},
{523, 1257},
{712, 1445},
{745, 1660},
{1126, 1663},
{1146, 1663},
{1360, 1725},
{1551, 1462},
{1800, 1418},
{1897, 960},
{1442, 661},
{1041, 501},
{752, 864},
{559, 1109},
},
{
{1627, 5166},
{1666, 5454},
{1762, 5607},
{1947, 5664},
{1952, 5644},
{2051, 5459},
{2023, 5140},
{1806, 4970},
{1663, 5003},
},
{
{848, 2443},
{929, 2648},
{1050, 2810},
{1166, 2744},
{1310, 2577},
{1270, 2372},
{1059, 2210},
{935, 2320},
},
},
nameLong = "West",
nameShort = "W",
},
}
| gpl-2.0 |
rzh/mongocraft | world/Plugins/Core/regen.lua | 6 | 1937 |
-- regen.lua
-- Implements the in-game and console commands for chunk regeneration
function HandleRegenCommand(a_Split, a_Player)
-- Check the params:
local numParams = #a_Split
if (numParams == 2) or (numParams > 3) then
SendMessage(a_Player, "Usage: '" .. a_Split[1] .. "' or '" .. a_Split[1] .. " <chunk x> <chunk z>'" )
return true
end
-- Get the coords of the chunk to regen:
local chunkX = a_Player:GetChunkX()
local chunkZ = a_Player:GetChunkZ()
if (numParams == 3) then
chunkX = tonumber(a_Split[2])
chunkZ = tonumber(a_Split[3])
if (chunkX == nil) then
SendMessageFailure(a_Player, "Not a number: '" .. a_Split[2] .. "'")
return true
end
if (chunkZ == nil) then
SendMessageFailure(a_Player, "Not a number: '" .. a_Split[3] .. "'")
return true
end
end
-- Regenerate the chunk:
SendMessageSuccess(a_Player, "Regenerating chunk [" .. chunkX .. ", " .. chunkZ .. "]...")
a_Player:GetWorld():RegenerateChunk(chunkX, chunkZ)
return true
end
function HandleConsoleRegen(a_Split)
-- Check the params:
local numParams = #a_Split
if ((numParams ~= 3) and (numParams ~= 4)) then
return true, "Usage: " .. a_Split[1] .. " <chunk x> <chunk z> [world]"
end
-- Get the coords of the chunk to regen:
local chunkX = tonumber(a_Split[2])
if (chunkX == nil) then
return true, "Not a number: '" .. a_Split[2] .. "'"
end
local chunkZ = tonumber(a_Split[3])
if (chunkZ == nil) then
return true, "Not a number: '" .. a_Split[3] .. "'"
end
-- Get the world to regen:
local world
if (a_Split[4] == nil) then
world = cRoot:Get():GetDefaultWorld()
else
world = cRoot:Get():GetWorld(a_Split[4])
if (world == nil) then
return true, "There's no world named '" .. a_Split[4] .. "'."
end
end
-- Regenerate the chunk:
world:RegenerateChunk(chunkX, chunkZ)
return true, "Regenerating chunk [" .. chunkX .. ", " .. chunkZ .. "] in world " .. world:GetName()
end
| apache-2.0 |
czfshine/Don-t-Starve | ZeroBraneStudio/lualibs/coxpcall/coxpcall.lua | 4 | 2272 | -------------------------------------------------------------------------------
-- Coroutine safe xpcall and pcall versions
--
-- Encapsulates the protected calls with a coroutine based loop, so errors can
-- be dealed without the usual Lua 5.x pcall/xpcall issues with coroutines
-- yielding inside the call to pcall or xpcall.
--
-- Authors: Roberto Ierusalimschy and Andre Carregal
-- Contributors: Thomas Harning Jr., Ignacio Burgueño, Fabio Mascarenhas
--
-- Copyright 2005 - Kepler Project (www.keplerproject.org)
--
-- $Id: coxpcall.lua,v 1.13 2008/05/19 19:20:02 mascarenhas Exp $
-------------------------------------------------------------------------------
-- Lua 5.2 makes this module a no-op
if _VERSION == "Lua 5.2" then
copcall = pcall
coxpcall = xpcall
return { pcall = pcall, xpcall = xpcall }
end
-------------------------------------------------------------------------------
-- Implements xpcall with coroutines
-------------------------------------------------------------------------------
local performResume, handleReturnValue
local oldpcall, oldxpcall = pcall, xpcall
local pack = table.pack or function(...) return {n = select("#", ...), ...} end
local unpack = table.unpack or unpack
function handleReturnValue(err, co, status, ...)
if not status then
return false, err(debug.traceback(co, (...)), ...)
end
if coroutine.status(co) == 'suspended' then
return performResume(err, co, coroutine.yield(...))
else
return true, ...
end
end
function performResume(err, co, ...)
return handleReturnValue(err, co, coroutine.resume(co, ...))
end
function coxpcall(f, err, ...)
local res, co = oldpcall(coroutine.create, f)
if not res then
local params = pack(...)
local newf = function() return f(unpack(params, 1, params.n)) end
co = coroutine.create(newf)
end
return performResume(err, co, ...)
end
-------------------------------------------------------------------------------
-- Implements pcall with coroutines
-------------------------------------------------------------------------------
local function id(trace, ...)
return ...
end
function copcall(f, ...)
return coxpcall(f, id, ...)
end
return { pcall = copcall, xpcall = coxpcall } | gpl-2.0 |
nvoron23/tarantool | test/box/access_misc.test.lua | 9 | 5391 | session = box.session
--
-- Check a double create space
--
s = box.schema.space.create('test')
s = box.schema.space.create('test')
--
-- Check a double drop space
--
s:drop()
s:drop()
--
-- Check double create user
--
box.schema.user.create('testus')
box.schema.user.create('testus')
s = box.schema.space.create('admin_space')
index = s:create_index('primary', {type = 'hash', parts = {1, 'NUM'}})
s:insert({1})
s:insert({2})
--
-- Check double grant and read access
--
box.schema.user.grant('testus', 'read', 'space', 'admin_space')
box.schema.user.grant('testus', 'read', 'space', 'admin_space')
session.su('testus')
s:select(1)
s:insert({3})
s:delete(1)
s:drop()
--
-- Check double revoke
--
session.su('admin')
box.schema.user.revoke('testus', 'read', 'space', 'admin_space')
box.schema.user.revoke('testus', 'read', 'space', 'admin_space')
session.su('testus')
s:select(1)
session.su('admin')
--
-- Check write access on space
--
box.schema.user.grant('testus', 'write', 'space', 'admin_space')
session.su('testus')
s:select(1)
s:delete(1)
s:insert({3})
s:drop()
session.su('admin')
--
-- Check double drop user
--
box.schema.user.drop('testus')
box.schema.user.drop('testus')
--
-- Check 'guest' user
--
session.su('guest')
session.uid()
box.space._user:select(1)
s:select(1)
s:insert({4})
s:delete({3})
s:drop()
gs = box.schema.space.create('guest_space')
box.schema.func.create('guest_func')
session.su('admin')
s:select()
--
-- Create user with universe read&write grants
-- and create this user session
--
box.schema.user.create('uniuser')
box.schema.user.grant('uniuser', 'read, write, execute', 'universe')
session.su('uniuser')
uid = session.uid()
--
-- Check universal user
-- Check delete currently authenticated user
--
box.schema.user.drop('uniuser')
--
--Check create, call and drop function
--
box.schema.func.create('uniuser_func')
function uniuser_func() return 'hello' end
uniuser_func()
box.schema.func.drop('uniuser_func')
--
-- Check create and drop space
--
us = box.schema.space.create('uniuser_space')
us:drop()
--
-- Check create and drop user
--
box.schema.user.create('uniuser_testus')
box.schema.user.drop('uniuser_testus')
--
-- Check access system and any spaces
--
box.space.admin_space:select()
box.space._user:select(1)
box.space._space:select(280)
us = box.schema.space.create('uniuser_space')
box.schema.func.create('uniuser_func')
session.su('admin')
box.schema.user.create('someuser')
box.schema.user.grant('someuser', 'read, write, execute', 'universe')
session.su('someuser')
--
-- Check drop objects of another user
--
s:drop()
us:drop()
box.schema.func.drop('uniuser_func')
box.schema.user.drop('uniuser_testus')
session.su('admin')
box.schema.func.drop('uniuser_func')
box.schema.user.drop('someuser')
box.schema.user.drop('uniuser_testus')
box.schema.user.drop('uniuser')
box.space._user:delete(uid)
s:drop()
--
-- Check write grant on _user
--
box.schema.user.create('testuser')
maxuid = box.space._user.index.primary:max()[1]
box.schema.user.grant('testuser', 'write', 'space', '_user')
session.su('testuser')
testuser_uid = session.uid()
box.space._user:delete(2)
box.space._user:select(1)
uid = box.space._user:insert{maxuid+1, session.uid(), 'someone', 'user'}[1]
box.space._user:delete(uid)
session.su('admin')
box.space._user:select(1)
box.space._user:delete(testuser_uid)
box.schema.user.revoke('testuser', 'write', 'space', '_user')
--
-- Check read grant on _user
--
box.schema.user.grant('testuser', 'read', 'space', '_user')
session.su('testuser')
box.space._user:delete(2)
box.space._user:select(1)
box.space._user:insert{uid, session.uid(), 'someone2', 'user'}
session.su('admin')
--
-- Check read grant on _index
--
box.schema.user.grant('testuser', 'read', 'space', '_index')
session.su('testuser')
box.space._index:select(272)
box.space._index:insert{512, 1,'owner','tree', 1, 1, 0,'num'}
session.su('admin')
box.schema.user.revoke('testuser', 'read, write, execute', 'universe')
--
-- Check that itertors check privileges
--
s = box.schema.space.create('glade')
box.schema.user.grant('testuser', 'read', 'space', 'glade')
index = s:create_index('primary', {unique = true, parts = {1, 'NUM', 2, 'STR'}})
s:insert({1, 'A'})
s:insert({2, 'B'})
s:insert({3, 'C'})
s:insert({4, 'D'})
t = {}
for key, v in s.index.primary:pairs(3, {iterator = 'GE'}) do table.insert (t, v) end
t
t = {}
session.su('testuser')
s:select()
for key, v in s.index.primary:pairs(3, {iterator = 'GE'}) do table.insert (t, v) end
t
t = {}
session.su('admin')
box.schema.user.revoke('testuser', 'read', 'space', 'glade')
box.schema.user.grant('testuser', 'write', 'space', 'glade')
session.su('testuser')
s:select()
for key, v in s.index.primary:pairs(1, {iterator = 'GE'}) do table.insert (t, v) end
t
t = {}
session.su('admin')
box.schema.user.grant('testuser', 'read, write, execute', 'space', 'glade')
session.su('testuser')
s:select()
for key, v in s.index.primary:pairs(3, {iterator = 'GE'}) do table.insert (t, v) end
t
t = {}
session.su('guest')
s:select()
for key, v in s.index.primary:pairs(3, {iterator = 'GE'}) do table.insert (t, v) end
t
t = {}
session.su('guest')
s:select()
for key, v in s.index.primary:pairs(3, {iterator = 'GE'}) do table.insert (t, v) end
t
session.su('admin')
box.schema.user.drop('testuser')
s:drop()
box.space._user:select()
box.space._space:select()
box.space._func:select()
session = nil
| bsd-2-clause |
Ameeralasdee/FROLA | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
rzh/mongocraft | world/Plugins/APIDump/Hooks/OnHopperPullingItem.lua | 44 | 1336 | return
{
HOOK_HOPPER_PULLING_ITEM =
{
CalledWhen = "A hopper is pulling an item from another block entity.",
DefaultFnName = "OnHopperPullingItem", -- also used as pagename
Desc = [[
This callback is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from another
block entity into its own internal storage. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper, with different
slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pulling the item" },
{ Name = "DstSlot", Type = "number", Notes = "The destination slot in the hopper's {{cItemGrid|internal storage}}" },
{ Name = "SrcBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = "The block entity that is losing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in SrcBlockEntity from which the item will be pulled" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event and the hopper will not pull the item.
]],
}, -- HOOK_HOPPER_PULLING_ITEM
}
| apache-2.0 |
czfshine/Don-t-Starve | data/scripts/screens/bigpopupdialog.lua | 1 | 2615 | local Screen = require "widgets/screen"
local Button = require "widgets/button"
local AnimButton = require "widgets/animbutton"
local ImageButton = require "widgets/imagebutton"
local Text = require "widgets/text"
local Image = require "widgets/image"
local Widget = require "widgets/widget"
local Menu = require "widgets/menu"
local BigPopupDialogScreen = Class(Screen, function(self, title, text, buttons, timeout)
Screen._ctor(self, "BigPopupDialogScreen")
--darken everything behind the dialog
self.black = self:AddChild(Image("images/global.xml", "square.tex"))
self.black:SetVRegPoint(ANCHOR_MIDDLE)
self.black:SetHRegPoint(ANCHOR_MIDDLE)
self.black:SetVAnchor(ANCHOR_MIDDLE)
self.black:SetHAnchor(ANCHOR_MIDDLE)
self.black:SetScaleMode(SCALEMODE_FILLSCREEN)
self.black:SetTint(0,0,0,.75)
self.proot = self:AddChild(Widget("ROOT"))
self.proot:SetVAnchor(ANCHOR_MIDDLE)
self.proot:SetHAnchor(ANCHOR_MIDDLE)
self.proot:SetPosition(0,0,0)
self.proot:SetScaleMode(SCALEMODE_PROPORTIONAL)
--throw up the background
self.bg = self.proot:AddChild(Image("images/globalpanels.xml", "panel_upsell_small.tex"))
self.bg:SetVRegPoint(ANCHOR_MIDDLE)
self.bg:SetHRegPoint(ANCHOR_MIDDLE)
self.bg:SetScale(1.2,1.2,1.2)
--if #buttons >2 then
-- self.bg:SetScale(2,1.2,1.2)
--end
--title
self.title = self.proot:AddChild(Text(TITLEFONT, 50))
self.title:SetPosition(0, 135, 0)
self.title:SetString(title)
--text
if JapaneseOnPS4() then
self.text = self.proot:AddChild(Text(BODYTEXTFONT, 28))
else
self.text = self.proot:AddChild(Text(BODYTEXTFONT, 30))
end
self.text:SetPosition(0, 5, 0)
self.text:SetString(text)
self.text:EnableWordWrap(true)
if JapaneseOnPS4() then
self.text:SetRegionSize(500, 300)
else
self.text:SetRegionSize(500, 200)
end
--create the menu itself
local button_w = 200
local space_between = 20
local spacing = button_w + space_between
local spacing = 200
self.menu = self.proot:AddChild(Menu(buttons, spacing, true))
self.menu:SetPosition(-(spacing*(#buttons-1))/2, -140, 0)
self.buttons = buttons
self.default_focus = self.menu
end)
function BigPopupDialogScreen:OnUpdate( dt )
if self.timeout then
self.timeout.timeout = self.timeout.timeout - dt
if self.timeout.timeout <= 0 then
self.timeout.cb()
end
end
return true
end
function BigPopupDialogScreen:OnControl(control, down)
if BigPopupDialogScreen._base.OnControl(self,control, down) then
return true
end
end
return BigPopupDialogScreen
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Gadgets/weapon_shield_merge.lua | 3 | 11540 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Shield Merge",
desc = "Implements shields as if they had a large shared battery between adjacent shields.",
author = "GoogleFrog",
date = "30 July 2016",
license = "None",
layer = 100,
enabled = true
}
end
local IterableMap = VFS.Include("LuaRules/Gadgets/Include/IterableMap.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitTeam = Spring.GetUnitTeam
local spGetTeamInfo = Spring.GetTeamInfo
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local modOptions = Spring.GetModOptions()
local MERGE_ENABLED = (modOptions.shield_merge == "share")
local PARTIAL_PENETRATE = (modOptions.shield_merge == "penetrate")
local SHIELD_ARMOR = Game.armorTypes.shield
local allyTeamShields = {}
local gameFrame = 0
local shieldDamages = {}
for i = 1, #WeaponDefs do
shieldDamages[i] = tonumber(WeaponDefs[i].customParams.shield_damage)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Network management
local function ShieldsAreTouching(shield1, shield2)
local xDiff = shield1.x - shield2.x
local zDiff = shield1.z - shield2.z
local yDiff = shield1.y - shield2.y
local sumRadius = shield1.shieldRadius + shield2.shieldRadius
return xDiff <= sumRadius and zDiff <= sumRadius and (xDiff*xDiff + yDiff*yDiff + zDiff*zDiff) < sumRadius*sumRadius
end
local otherID
local otherData
local otherMobile
local function UpdateLink(unitID, unitData)
if unitID ~= otherID and (otherMobile or unitData.mobile) then
local currentlyNeighbors = (otherData.neighbors.InMap(unitID) or unitData.neighbors.InMap(otherID))
local touching = ShieldsAreTouching(unitData, otherData)
if currentlyNeighbors and not touching then
--Spring.Utilities.UnitEcho(unitID, "-")
--Spring.Utilities.UnitEcho(otherID, "-")
otherData.neighbors.Remove(unitID)
unitData.neighbors.Remove(otherID)
elseif touching and not currentlyNeighbors then
--Spring.Utilities.UnitEcho(unitID, "+")
--Spring.Utilities.UnitEcho(otherID, "+")
otherData.neighbors.Add(unitID)
unitData.neighbors.Add(otherID)
end
end
end
local function AdjustLinks(unitID, shieldUnits)
otherID = unitID
otherData = shieldUnits.Get(unitID)
if otherData then
if otherData.mobilesAdded then
otherMobile = otherData.mobile
else
otherData.mobilesAdded = true
otherMobile = true
end
shieldUnits.Apply(UpdateLink)
end
end
local function PossiblyUpdateLinks(unitID, allyTeamID)
local shieldUnits = allyTeamShields[allyTeamID]
local unitData = shieldUnits.Get(unitID)
if not unitData then
return
end
if unitData.nextUpdateTime < gameFrame then
unitData.nextUpdateTime = gameFrame + 15
AdjustLinks(unitID, shieldUnits)
end
end
local function RemoveNeighbor(unitID, _, _, thisShieldTeam, toRemoveID)
if thisShieldTeam.InMap(unitID) then
thisShieldTeam.Get(unitID).neighbors.Remove(toRemoveID)
end
end
local function RemoveUnitFromNeighbors(thisShieldTeam, unitID, neighbors)
neighbors.Apply(RemoveNeighbor, thisShieldTeam, unitID)
end
local function UpdatePosition(unitID, unitData)
if unitData.mobile then
local ux,uy,uz = spGetUnitPosition(unitID)
unitData.x = ux
unitData.y = uy
unitData.z = uz
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unit tracking
function gadget:UnitCreated(unitID, unitDefID)
-- only count finished buildings
local stunned_or_inbuild, stunned, inbuild = spGetUnitIsStunned(unitID)
if stunned_or_inbuild ~= nil and inbuild then
return
end
local ud = UnitDefs[unitDefID]
local shieldWeaponDefID
local shieldNum = -1
if ud.customParams.dynamic_comm then
if GG.Upgrades_UnitShieldDef then
shieldWeaponDefID, shieldNum = GG.Upgrades_UnitShieldDef(unitID)
end
else
shieldWeaponDefID = ud.shieldWeaponDef
end
if shieldWeaponDefID then
local shieldWep = WeaponDefs[shieldWeaponDefID]
local allyTeamID = spGetUnitAllyTeam(unitID)
if not (allyTeamShields[allyTeamID] and allyTeamShields[allyTeamID].InMap(unitID)) then
-- not need to redo table if already have table (UnitFinished() will call this function 2nd time)
allyTeamShields[allyTeamID] = allyTeamShields[allyTeamID] or IterableMap.New()
local ux,uy,uz = spGetUnitPosition(unitID)
local shieldData = {
shieldRadius = shieldWep.shieldRadius,
neighbors = IterableMap.New(),
allyTeamID = allyTeamID,
nextUpdateTime = gameFrame,
x = ux,
y = uy,
z = uz,
mobile = Spring.Utilities.getMovetype(ud) and true
}
allyTeamShields[allyTeamID].Add(unitID, shieldData)
AdjustLinks(unitID, allyTeamShields[allyTeamID])
end
end
end
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
gadget:UnitCreated(unitID, unitDefID)
end
function gadget:UnitDestroyed(unitID, unitDefID)
local allyTeamID = spGetUnitAllyTeam(unitID)
if allyTeamShields[allyTeamID] and allyTeamShields[allyTeamID].InMap(unitID) then
local unitData = allyTeamShields[allyTeamID].Get(unitID)
if unitData then
RemoveUnitFromNeighbors(allyTeamShields[allyTeamID], unitID, unitData.neighbors)
end
allyTeamShields[allyTeamID].Remove(unitID)
end
end
function gadget:UnitGiven(unitID, unitDefID, unitTeam, oldTeam)
local _,_,_,_,_,oldAllyTeam = spGetTeamInfo(oldTeam)
local allyTeamID = spGetUnitAllyTeam(unitID)
if allyTeamID and allyTeamShields[oldAllyTeam] and allyTeamShields[oldAllyTeam].InMap(unitID) then
local unitData
if allyTeamShields[oldAllyTeam] and allyTeamShields[oldAllyTeam].InMap(unitID) then
unitData = allyTeamShields[oldAllyTeam].Get(unitID)
allyTeamShields[oldAllyTeam].Remove(unitID)
RemoveUnitFromNeighbors(allyTeamShields[oldAllyTeam], unitID, unitData.neighbors)
unitData.neighbors = IterableMap.New()
unitData.allyTeamID = allyTeamID
end
if unitData then
--Note: wont be problem when NIL when nanoframe is captured because is always filled with new value when unit finish
allyTeamShields[allyTeamID] = allyTeamShields[allyTeamID] or IterableMap.New()
allyTeamShields[allyTeamID].Add(unitID, unitData)
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Hit and update handling
local beamMultiHitException = {
[UnitDefNames["amphassault"].id] = true,
[UnitDefNames["striderdetriment"].id] = true,
}
local repeatedHits = {}
local penetrationPower = {}
function gadget:GameFrame(n)
repeatedHits = {} -- Feel sorry for GC
if not MERGE_ENABLED then
return
end
gameFrame = n
if n%13 == 7 then
for allyTeamID, unitList in pairs(allyTeamShields) do
unitList.ApplyNoArg(UpdatePosition)
end
end
end
-- Evil
local totalCharge = 0
local shieldCharges = nil
local chargeProportion = 1
local function SumCharge(unitID, _, index)
shieldCharges[index] = select(2, Spring.GetUnitShieldState(unitID)) or 0
totalCharge = totalCharge + shieldCharges[index]
end
-- Double evil
local function SetCharge(unitID, _, index)
Spring.SetUnitShieldState(unitID, -1, true, shieldCharges[index]*chargeProportion)
end
local function DrainShieldAndCheckProjectilePenetrate(unitID, damage, realDamage, proID)
local _, charge = Spring.GetUnitShieldState(unitID)
local origDamage = damage
if PARTIAL_PENETRATE and penetrationPower[proID] then
damage = penetrationPower[proID]
penetrationPower[proID] = nil
end
if charge and damage < charge then
Spring.SetUnitShieldState(unitID, -1, true, charge - damage + realDamage)
return false
elseif MERGE_ENABLED then
damage = damage - charge
local allyTeamID = Spring.GetUnitAllyTeam(unitID)
PossiblyUpdateLinks(unitID, allyTeamID)
local shieldData = allyTeamShields[allyTeamID].Get(unitID)
totalCharge = 0
shieldCharges = {}
shieldData.neighbors.ApplyNoArg(SumCharge)
if damage < totalCharge then
Spring.SetUnitShieldState(unitID, -1, true, realDamage)
chargeProportion = 1 - damage/totalCharge
shieldData.neighbors.ApplyNoArg(SetCharge)
shieldCharges = nil
return false
end
shieldCharges = nil
elseif PARTIAL_PENETRATE and proID then
local remainingPower = damage - charge
penetrationPower[proID] = remainingPower
Spring.SetUnitShieldState(unitID, -1, true, 0)
if Spring.GetProjectileDefID(proID) then -- some projectile IDs are not integers.
local gravity = Spring.GetProjectileGravity(proID)
local vx, vy, vz = Spring.GetProjectileVelocity(proID)
local mult = 0.75 + 0.25*remainingPower/origDamage
Spring.SetProjectileGravity(proID, gravity*mult^2)
Spring.SetProjectileVelocity(proID, vx*mult, vy*mult, vz*mult)
end
end
return true
end
function gadget:ShieldPreDamaged(proID, proOwnerID, shieldEmitterWeaponNum, shieldCarrierUnitID, bounceProjectile, beamEmitter, beamCarrierID)
local weaponDefID
local hackyProID
if (not Spring.ValidUnitID(shieldCarrierUnitID)) or Spring.GetUnitIsDead(shieldCarrierUnitID) then
return false
end
if proID == -1 then
local unitDefID = Spring.GetUnitDefID(beamCarrierID)
-- Beam weapons hit shields four times per frame.
-- No idea why.
if not beamMultiHitException[unitDefID] then
hackyProID = beamCarrierID + beamEmitter/64
repeatedHits[shieldCarrierUnitID] = repeatedHits[shieldCarrierUnitID] or {}
if repeatedHits[shieldCarrierUnitID][hackyProID] ~= nil then
return repeatedHits[shieldCarrierUnitID][hackyProID]
end
end
-- Beam weapon
local ud = beamCarrierID and UnitDefs[unitDefID]
if not ud then
return true
end
weaponDefID = ud.weapons[beamEmitter].weaponDef
else
-- Projectile
weaponDefID = Spring.GetProjectileDefID(proID)
end
if not weaponDefID then
return true
end
local wd = WeaponDefs[weaponDefID]
local damage = shieldDamages[weaponDefID]
local projectilePasses = DrainShieldAndCheckProjectilePenetrate(shieldCarrierUnitID, damage, wd.damages[SHIELD_ARMOR], hackyProID or proID)
if hackyProID then
repeatedHits[shieldCarrierUnitID][hackyProID] = projectilePasses
end
return projectilePasses
end
function gadget:Initialize()
GG.DrainShieldAndCheckProjectilePenetrate = DrainShieldAndCheckProjectilePenetrate
if MERGE_ENABLED then
for _,unitID in ipairs(Spring.GetAllUnits()) do
local teamID = spGetUnitTeam(unitID)
local unitDefID = spGetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
else
gadgetHandler:RemoveCallIn("UnitCreated")
gadgetHandler:RemoveCallIn("UnitFinished")
gadgetHandler:RemoveCallIn("UnitDestroyed")
gadgetHandler:RemoveCallIn("UnitGiven")
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/components/pollinator.lua | 1 | 1292 | local Pollinator = Class(function(self, inst)
self.inst = inst
self.flowers = {}
self.distance = 5
self.maxdensity = 4
self.collectcount = 5
self.target = nil
self.inst:AddTag("pollinator")
end)
function Pollinator:GetDebugString()
return string.format("flowers: %d, cancreate: %s", #self.flowers, tostring(self:HasCollectedEnough() ) )
end
function Pollinator:Pollinate(flower)
if self:CanPollinate(flower) then
table.insert(self.flowers, flower)
self.target = nil
end
end
function Pollinator:CanPollinate(flower)
return flower and flower:HasTag("flower") and not table.contains(self.flowers, flower)
end
function Pollinator:HasCollectedEnough()
return #self.flowers >= self.collectcount
end
function Pollinator:CreateFlower()
if self:HasCollectedEnough() then
local parentFlower = GetRandomItem(self.flowers)
local flower = SpawnPrefab(parentFlower.prefab)
flower.Transform:SetPosition(self.inst.Transform:GetWorldPosition())
self.flowers = {}
end
end
function Pollinator:CheckFlowerDensity()
local x,y,z = self.inst.Transform:GetWorldPosition()
local nearbyflowers = TheSim:FindEntities(x,y,z, self.distance, "flower")
return #nearbyflowers < self.maxdensity
end
return Pollinator
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/map/static_layouts/wasphive_grass_easy.lua | 1 | 12735 | return {
version = "1.1",
luaversion = "5.1",
orientation = "orthogonal",
width = 12,
height = 12,
tilewidth = 16,
tileheight = 16,
properties = {},
tilesets = {
{
name = "tiles",
firstgid = 1,
tilewidth = 64,
tileheight = 64,
spacing = 0,
margin = 0,
image = "../../../../tools/tiled/dont_starve/tiles.png",
imagewidth = 512,
imageheight = 128,
properties = {},
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "BG_TILES",
x = 0,
y = 0,
width = 12,
height = 12,
visible = true,
opacity = 1,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 6, 6, 0, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0
}
},
{
type = "objectgroup",
name = "FG_OBJECTS",
visible = true,
opacity = 1,
properties = {},
objects = {
{
name = "",
type = "grass",
shape = "rectangle",
x = 59,
y = 118,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 61,
y = 85,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "wasphive",
shape = "rectangle",
x = 78,
y = 86,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 55,
y = 72,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 61,
y = 101,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 64,
y = 157,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 111,
y = 89,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 66,
y = 53,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "wasphive",
shape = "rectangle",
x = 125,
y = 53,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "wasphive",
shape = "rectangle",
x = 60,
y = 128,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 86,
y = 38,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 80,
y = 148,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 93,
y = 161,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 99,
y = 58,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 83,
y = 118,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 83,
y = 100,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 93,
y = 133,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 103,
y = 38,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 95,
y = 72,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 118,
y = 23,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 125,
y = 149,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 115,
y = 163,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 125,
y = 117,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 125,
y = 85,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 114,
y = 104,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 113,
y = 135,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 144,
y = 27,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 77,
y = 73,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 118,
y = 71,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 149,
y = 54,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 100,
y = 115,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 149,
y = 86,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 145,
y = 102,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 144,
y = 133,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 157,
y = 37,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 152,
y = 70,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 130,
y = 35,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 44,
y = 151,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 29,
y = 165,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 83,
y = 55,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 38,
y = 117,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 34,
y = 90,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 29,
y = 101,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 33,
y = 133,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 63,
y = 140,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 35,
y = 60,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 97,
y = 93,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 52,
y = 54,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 69,
y = 33,
width = 0,
height = 0,
visible = true,
properties = {}
}
}
}
}
}
| gpl-2.0 |
starkos/premake-core | modules/android/vsandroid_vcxproj.lua | 4 | 17615 | --
-- android/vsandroid_vcxproj.lua
-- vs-android integration for vstudio.
-- Copyright (c) 2012-2015 Manu Evans and the Premake project
--
local p = premake
p.modules.vsandroid = { }
local android = p.modules.android
local vsandroid = p.modules.vsandroid
local vc2010 = p.vstudio.vc2010
local vstudio = p.vstudio
local project = p.project
local config = p.config
--
-- Utility functions
--
local function setBoolOption(optionName, flag, value)
if flag ~= nil then
vc2010.element(optionName, nil, value)
end
end
--
-- Add android tools to vstudio actions.
--
if vstudio.vs2010_architectures ~= nil then
if _ACTION >= "vs2015" then
vstudio.vs2010_architectures.arm = "ARM"
else
vstudio.vs2010_architectures.android = "Android"
end
end
--
-- Extend global properties
--
premake.override(vc2010.elements, "globals", function (oldfn, prj)
local elements = oldfn(prj)
if prj.system == premake.ANDROID and prj.kind ~= premake.PACKAGING then
-- Remove "IgnoreWarnCompileDuplicatedFilename".
local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename)
table.remove(elements, pos)
elements = table.join(elements, {
android.androidApplicationType
})
end
return elements
end)
premake.override(vc2010.elements, "globalsCondition", function (oldfn, prj, cfg)
local elements = oldfn(prj, cfg)
if cfg.system == premake.ANDROID and cfg.system ~= prj.system and cfg.kind ~= premake.PACKAGING then
elements = table.join(elements, {
android.androidApplicationType
})
end
return elements
end)
function android.androidApplicationType(cfg)
vc2010.element("Keyword", nil, "Android")
vc2010.element("RootNamespace", nil, "%s", cfg.project.name)
if _ACTION >= "vs2019" then
vc2010.element("MinimumVisualStudioVersion", nil, "16.0")
elseif _ACTION >= "vs2017" then
vc2010.element("MinimumVisualStudioVersion", nil, "15.0")
elseif _ACTION >= "vs2015" then
vc2010.element("MinimumVisualStudioVersion", nil, "14.0")
end
vc2010.element("ApplicationType", nil, "Android")
if _ACTION >= "vs2017" then
vc2010.element("ApplicationTypeRevision", nil, "3.0")
elseif _ACTION >= "vs2015" then
vc2010.element("ApplicationTypeRevision", nil, "2.0")
else
vc2010.element("ApplicationTypeRevision", nil, "1.0")
end
end
--
-- Extend configurationProperties.
--
premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind ~= p.UTILITY and cfg.kind ~= p.PACKAGING and cfg.system == premake.ANDROID then
table.remove(elements, table.indexof(elements, vc2010.characterSet))
table.remove(elements, table.indexof(elements, vc2010.wholeProgramOptimization))
table.remove(elements, table.indexof(elements, vc2010.windowsSDKDesktopARMSupport))
elements = table.join(elements, {
android.androidAPILevel,
android.androidStlType,
})
if _ACTION >= "vs2015" then
elements = table.join(elements, {
android.thumbMode,
})
end
end
return elements
end)
function android.androidAPILevel(cfg)
if cfg.androidapilevel ~= nil then
vc2010.element("AndroidAPILevel", nil, "android-" .. cfg.androidapilevel)
end
end
function android.androidStlType(cfg)
if cfg.stl ~= nil then
local stlType = {
["none"] = "system",
["gabi++"] = "gabi++",
["stlport"] = "stlport",
["gnu"] = "gnustl",
["libc++"] = "c++",
}
local postfix = iif(cfg.staticruntime == "On", "_static", "_shared")
local runtimeLib = iif(cfg.stl == "none", "system", stlType[cfg.stl] .. postfix)
if _ACTION >= "vs2015" then
vc2010.element("UseOfStl", nil, runtimeLib)
else
vc2010.element("AndroidStlType", nil, runtimeLib)
end
end
end
function android.thumbMode(cfg)
if cfg.thumbmode ~= nil then
local thumbMode =
{
thumb = "Thumb",
arm = "ARM",
disabled = "Disabled",
}
vc2010.element("ThumbMode", nil, thumbMode[cfg.thumbmode])
end
end
-- Note: this function is already patched in by vs2012...
premake.override(vc2010, "platformToolset", function(oldfn, cfg)
if cfg.system ~= premake.ANDROID then
return oldfn(cfg)
end
if _ACTION >= "vs2015" then
local gcc_map = {
["4.6"] = "GCC_4_6",
["4.8"] = "GCC_4_8",
["4.9"] = "GCC_4_9",
}
local clang_map = {
["3.4"] = "Clang_3_4",
["3.5"] = "Clang_3_5",
["3.6"] = "Clang_3_6",
["3.8"] = "Clang_3_8",
["5.0"] = "Clang_5_0",
}
if cfg.toolchainversion ~= nil then
local map = iif(cfg.toolset == "gcc", gcc_map, clang_map)
local ts = map[cfg.toolchainversion]
if ts == nil then
p.error('Invalid toolchainversion for the selected toolset (%s).', cfg.toolset or "clang")
end
vc2010.element("PlatformToolset", nil, ts)
end
else
local archMap = {
arm = "armv5te", -- should arm5 be default? vs-android thinks so...
arm5 = "armv5te",
arm7 = "armv7-a",
mips = "mips",
x86 = "x86",
}
local arch = cfg.architecture or "arm"
if (cfg.architecture ~= nil or cfg.toolchainversion ~= nil) and archMap[arch] ~= nil then
local defaultToolsetMap = {
arm = "arm-linux-androideabi-",
armv5 = "arm-linux-androideabi-",
armv7 = "arm-linux-androideabi-",
aarch64 = "aarch64-linux-android-",
mips = "mipsel-linux-android-",
mips64 = "mips64el-linux-android-",
x86 = "x86-",
x86_64 = "x86_64-",
}
local toolset = defaultToolsetMap[arch]
if cfg.toolset == "clang" then
error("The clang toolset is not yet supported by vs-android", 2)
toolset = toolset .. "clang"
elseif cfg.toolset and cfg.toolset ~= "gcc" then
error("Toolset not supported by the android NDK: " .. cfg.toolset, 2)
end
local version = cfg.toolchainversion or iif(cfg.toolset == "clang", "3.5", "4.9")
vc2010.element("PlatformToolset", nil, toolset .. version)
vc2010.element("AndroidArch", nil, archMap[arch])
end
end
end)
--
-- Extend clCompile.
--
premake.override(vc2010.elements, "clCompile", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.system == premake.ANDROID then
elements = table.join(elements, {
android.debugInformation,
android.strictAliasing,
android.fpu,
android.pic,
android.shortEnums,
android.cStandard,
android.cppStandard,
})
if _ACTION >= "vs2015" then
table.remove(elements, table.indexof(elements, vc2010.debugInformationFormat))
-- Android has C[pp]LanguageStandard instead.
table.remove(elements, table.indexof(elements, vc2010.languageStandard))
-- Ignore multiProcessorCompilation for android projects, they use UseMultiToolTask instead.
table.remove(elements, table.indexof(elements, vc2010.multiProcessorCompilation))
-- minimalRebuild also ends up in android projects somehow.
table.remove(elements, table.indexof(elements, vc2010.minimalRebuild))
-- VS has NEON support through EnableNeonCodegen.
table.replace(elements, vc2010.enableEnhancedInstructionSet, android.enableEnhancedInstructionSet)
-- precompiledHeaderFile support.
table.replace(elements, vc2010.precompiledHeaderFile, android.precompiledHeaderFile)
end
end
return elements
end)
function android.precompiledHeaderFile(fileName, cfg)
-- Doesn't work for project-relative paths.
vc2010.element("PrecompiledHeaderFile", nil, "%s", path.getabsolute(path.rebase(fileName, cfg.basedir, cfg.location)))
end
function android.debugInformation(cfg)
if cfg.flags.Symbols then
_p(3,'<GenerateDebugInformation>true</GenerateDebugInformation>')
end
end
function android.strictAliasing(cfg)
if cfg.strictaliasing ~= nil then
vc2010.element("StrictAliasing", nil, iif(cfg.strictaliasing == "Off", "false", "true"))
end
end
function android.fpu(cfg)
if cfg.fpu ~= nil then
_p(3,'<SoftFloat>true</SoftFloat>', iif(cfg.fpu == "Software", "true", "false"))
end
end
function android.pic(cfg)
if cfg.pic ~= nil then
vc2010.element("PositionIndependentCode", nil, iif(cfg.pic == "On", "true", "false"))
end
end
function android.verboseCompiler(cfg)
setBoolOption("Verbose", cfg.flags.VerboseCompiler, "true")
end
function android.undefineAllPreprocessorDefinitions(cfg)
setBoolOption("UndefineAllPreprocessorDefinitions", cfg.flags.UndefineAllPreprocessorDefinitions, "true")
end
function android.showIncludes(cfg)
setBoolOption("ShowIncludes", cfg.flags.ShowIncludes, "true")
end
function android.dataLevelLinking(cfg)
setBoolOption("DataLevelLinking", cfg.flags.DataLevelLinking, "true")
end
function android.shortEnums(cfg)
setBoolOption("UseShortEnums", cfg.flags.UseShortEnums, "true")
end
function android.cStandard(cfg)
local c_langmap = {
["C98"] = "c98",
["C99"] = "c99",
["C11"] = "c11",
["gnu99"] = "gnu99",
["gnu11"] = "gnu11",
}
if c_langmap[cfg.cdialect] ~= nil then
vc2010.element("CLanguageStandard", nil, c_langmap[cfg.cdialect])
end
end
function android.cppStandard(cfg)
local cpp_langmap = {
["C++98"] = "c++98",
["C++11"] = "c++11",
["C++14"] = "c++1y",
["C++17"] = "c++1z",
["C++latest"] = "c++1z",
["gnu++98"] = "gnu++98",
["gnu++11"] = "gnu++11",
["gnu++14"] = "gnu++1y",
["gnu++17"] = "gnu++1z",
}
if cpp_langmap[cfg.cppdialect] ~= nil then
vc2010.element("CppLanguageStandard", nil, cpp_langmap[cfg.cppdialect])
end
end
p.override(vc2010, "additionalCompileOptions", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
local opts = cfg.buildoptions
if cfg.disablewarnings and #cfg.disablewarnings > 0 then
for _, warning in ipairs(cfg.disablewarnings) do
table.insert(opts, '-Wno-' .. warning)
end
end
-- -fvisibility=<>
if cfg.visibility ~= nil then
table.insert(opts, p.tools.gcc.cxxflags.visibility[cfg.visibility])
end
if #opts > 0 then
opts = table.concat(opts, " ")
vc2010.element("AdditionalOptions", condition, '%s %%(AdditionalOptions)', opts)
end
else
oldfn(cfg, condition)
end
end)
p.override(vc2010, "warningLevel", function(oldfn, cfg)
if _ACTION >= "vs2015" and cfg.system == p.ANDROID and cfg.warnings and cfg.warnings ~= "Off" then
vc2010.element("WarningLevel", nil, "EnableAllWarnings")
elseif (_ACTION >= "vs2015" and cfg.system == p.ANDROID and cfg.warnings) or not (_ACTION >= "vs2015" and cfg.system == p.ANDROID) then
oldfn(cfg)
end
end)
premake.override(vc2010, "clCompilePreprocessorDefinitions", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
vc2010.preprocessorDefinitions(cfg, cfg.defines, false, condition)
else
oldfn(cfg, condition)
end
end)
premake.override(vc2010, "exceptionHandling", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
-- Note: Android defaults to 'off'
local exceptions = {
On = "Enabled",
Off = "Disabled",
UnwindTables = "UnwindTables",
}
if _ACTION >= "vs2015" then
if exceptions[cfg.exceptionhandling] ~= nil then
vc2010.element("ExceptionHandling", condition, exceptions[cfg.exceptionhandling])
end
else
if cfg.exceptionhandling == premake.ON then
vc2010.element("GccExceptionHandling", condition, "true")
end
end
else
oldfn(cfg, condition)
end
end)
function android.enableEnhancedInstructionSet(cfg)
if cfg.vectorextensions == "NEON" then
vc2010.element("EnableNeonCodegen", nil, "true")
end
end
premake.override(vc2010, "runtimeTypeInfo", function(oldfn, cfg, condition)
if cfg.system == premake.ANDROID then
-- Note: Android defaults to 'off'
if cfg.rtti == premake.ON then
vc2010.element("RuntimeTypeInfo", condition, "true")
end
else
oldfn(cfg, condition)
end
end)
--
-- Extend Link.
--
premake.override(vc2010, "generateDebugInformation", function(oldfn, cfg)
-- Note: Android specifies the debug info in the clCompile section
if cfg.system ~= premake.ANDROID then
oldfn(cfg)
end
end)
--
-- Add android tools to vstudio actions.
--
premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.system == premake.ANDROID and _ACTION < "vs2015" then
elements = table.join(elements, {
android.antBuild,
})
end
return elements
end)
function android.antPackage(cfg)
p.push('<AntPackage>')
if cfg.androidapplibname ~= nil then
vc2010.element("AndroidAppLibName", nil, cfg.androidapplibname)
else
vc2010.element("AndroidAppLibName", nil, "$(RootNamespace)")
end
p.pop('</AntPackage>')
end
function android.antBuild(cfg)
if cfg.kind == premake.STATICLIB or cfg.kind == premake.SHAREDLIB then
return
end
_p(2,'<AntBuild>')
_p(3,'<AntBuildType>%s</AntBuildType>', iif(premake.config.isDebugBuild(cfg), "Debug", "Release"))
_p(2,'</AntBuild>')
end
premake.override(vc2010, "additionalCompileOptions", function(oldfn, cfg, condition)
if cfg.system == premake.ANDROID then
vsandroid.additionalOptions(cfg, condition)
end
return oldfn(cfg, condition)
end)
premake.override(vc2010.elements, "user", function(oldfn, cfg)
if cfg.system == p.ANDROID then
return {}
else
return oldfn(cfg)
end
end)
--
-- Add options unsupported by vs-android UI to <AdvancedOptions>.
--
function vsandroid.additionalOptions(cfg)
if _ACTION >= "vs2015" then
else
local function alreadyHas(t, key)
for _, k in ipairs(t) do
if string.find(k, key) then
return true
end
end
return false
end
if not cfg.architecture or string.startswith(cfg.architecture, "arm") then
-- we might want to define the arch to generate better code
-- if not alreadyHas(cfg.buildoptions, "-march=") then
-- if cfg.architecture == "armv6" then
-- table.insert(cfg.buildoptions, "-march=armv6")
-- elseif cfg.architecture == "armv7" then
-- table.insert(cfg.buildoptions, "-march=armv7")
-- end
-- end
-- ARM has a comprehensive set of floating point options
if cfg.fpu ~= "Software" and cfg.floatabi ~= "soft" then
if cfg.architecture == "armv7" then
-- armv7 always has VFP, may not have NEON
if not alreadyHas(cfg.buildoptions, "-mfpu=") then
if cfg.vectorextensions == "NEON" then
table.insert(cfg.buildoptions, "-mfpu=neon")
elseif cfg.fpu == "Hardware" or cfg.floatabi == "softfp" or cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfpu=vfpv3-d16") -- d16 is the lowest common denominator
end
end
if not alreadyHas(cfg.buildoptions, "-mfloat-abi=") then
if cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfloat-abi=hard")
else
-- Android should probably use softfp by default for compatibility
table.insert(cfg.buildoptions, "-mfloat-abi=softfp")
end
end
else
-- armv5/6 may not have VFP
if not alreadyHas(cfg.buildoptions, "-mfpu=") then
if cfg.fpu == "Hardware" or cfg.floatabi == "softfp" or cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfpu=vfp")
end
end
if not alreadyHas(cfg.buildoptions, "-mfloat-abi=") then
if cfg.floatabi == "softfp" then
table.insert(cfg.buildoptions, "-mfloat-abi=softfp")
elseif cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfloat-abi=hard")
end
end
end
elseif cfg.floatabi == "soft" then
table.insert(cfg.buildoptions, "-mfloat-abi=soft")
end
if cfg.endian == "Little" then
table.insert(cfg.buildoptions, "-mlittle-endian")
elseif cfg.endian == "Big" then
table.insert(cfg.buildoptions, "-mbig-endian")
end
elseif cfg.architecture == "mips" then
-- TODO...
if cfg.vectorextensions == "MXU" then
table.insert(cfg.buildoptions, "-mmxu")
end
elseif cfg.architecture == "x86" then
-- TODO...
end
end
end
--
-- Disable subsystem.
--
p.override(vc2010, "subSystem", function(oldfn, cfg)
if cfg.system ~= p.ANDROID then
return oldfn(cfg)
end
end)
--
-- Remove .lib and list in LibraryDependencies instead of AdditionalDependencies.
--
p.override(vc2010, "additionalDependencies", function(oldfn, cfg, explicit)
if cfg.system == p.ANDROID then
local links = {}
-- If we need sibling projects to be listed explicitly, grab them first
if explicit then
links = config.getlinks(cfg, "siblings", "fullpath")
end
-- Then the system libraries, which come undecorated
local system = config.getlinks(cfg, "system", "name")
for i = 1, #system do
local link = system[i]
table.insert(links, link)
end
-- TODO: When to use LibraryDependencies vs AdditionalDependencies
if #links > 0 then
links = path.translate(table.concat(links, ";"))
vc2010.element("LibraryDependencies", nil, "%%(LibraryDependencies);%s", links)
end
else
return oldfn(cfg, explicit)
end
end)
function android.useMultiToolTask(cfg)
-- Android equivalent of 'MultiProcessorCompilation'
if cfg.flags.MultiProcessorCompile then
vc2010.element("UseMultiToolTask", nil, "true")
end
end
premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg)
if cfg.system == p.ANDROID then
return table.join(oldfn(cfg), {
android.useMultiToolTask,
})
else
return oldfn(cfg)
end
end)
--
-- Disable override of OutDir. This is breaking deployment.
--
p.override(vc2010, "outDir", function(oldfn, cfg)
if cfg.system ~= p.ANDROID then
return oldfn(cfg)
end
end)
| bsd-3-clause |
ho3einkj/bot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
mohammad8/test1 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
aliadddd/ssbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
czfshine/Don-t-Starve | data/DLC0001/scripts/prefabs/thulecite_pieces.lua | 1 | 1089 | local assets =
{
Asset("ANIM", "anim/thulecite_pieces.zip"),
}
local function fn(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("thulecite_pieces")
inst.AnimState:SetBuild("thulecite_pieces")
inst.AnimState:PlayAnimation("anim")
inst:AddComponent("edible")
inst.components.edible.foodtype = "ELEMENTAL"
inst.components.edible.hungervalue = 1
inst:AddComponent("tradable")
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst:AddComponent("stackable")
inst:AddComponent("bait")
inst:AddTag("molebait")
inst:AddComponent("repairer")
inst.components.repairer.repairmaterial = "thulecite"
inst.components.repairer.healthrepairvalue = TUNING.REPAIR_THULECITE_PIECES_HEALTH
inst.components.repairer.workrepairvalue = TUNING.REPAIR_THULECITE_PIECES_WORK
inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM
return inst
end
return Prefab( "common/inventory/thulecite_pieces", fn, assets)
| gpl-2.0 |
nimaghorbani/dozdi9 | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
mercury233/ygopro-scripts | c38723936.lua | 2 | 1605 | --クイズ
function c38723936.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c38723936.cost)
e1:SetTarget(c38723936.target)
e1:SetOperation(c38723936.activate)
c:RegisterEffect(e1)
end
function c38723936.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if e:IsHasType(EFFECT_TYPE_ACTIVATE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH+EFFECT_FLAG_CLIENT_HINT)
e1:SetDescription(CARD_QUESTION)
e1:SetTargetRange(0,1)
e1:SetReset(RESET_CHAIN)
Duel.RegisterEffect(e1,tp)
end
end
function c38723936.filter(c)
return c:IsType(TYPE_MONSTER) and c:IsAbleToRemove()
end
function c38723936.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.IsExistingTarget(c38723936.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,nil,1,tp,0)
end
function c38723936.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c38723936.filter,tp,LOCATION_GRAVE,0,nil)
if g:GetCount()==0 then return end
local last=g:GetFirst()
local tc=g:GetNext()
while tc do
if tc:GetSequence()<last:GetSequence() then last=tc end
tc=g:GetNext()
end
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_CODE)
local ac=Duel.AnnounceCard(1-tp,TYPE_MONSTER,OPCODE_ISTYPE)
if ac~=last:GetCode() then
Duel.SpecialSummon(last,0,tp,tp,false,false,POS_FACEUP)
else
Duel.Remove(last,POS_FACEUP,REASON_EFFECT)
end
end
| gpl-2.0 |
linushsao/marsu_game-linus-v0.2 | mods/technical/mesecons/mesecons/internal.lua | 3 | 18746 | -- Internal.lua - The core of mesecons
--
-- For more practical developer resources see http://mesecons.net/developers.php
--
-- Function overview
-- mesecon.get_effector(nodename) --> Returns the mesecons.effector -specifictation in the nodedef by the nodename
-- mesecon.get_receptor(nodename) --> Returns the mesecons.receptor -specifictation in the nodedef by the nodename
-- mesecon.get_conductor(nodename) --> Returns the mesecons.conductor-specifictation in the nodedef by the nodename
-- mesecon.get_any_inputrules (node) --> Returns the rules of a node if it is a conductor or an effector
-- mesecon.get_any_outputrules (node) --> Returns the rules of a node if it is a conductor or a receptor
-- RECEPTORS
-- mesecon.is_receptor(nodename) --> Returns true if nodename is a receptor
-- mesecon.is_receptor_on(nodename --> Returns true if nodename is an receptor with state = mesecon.state.on
-- mesecon.is_receptor_off(nodename) --> Returns true if nodename is an receptor with state = mesecon.state.off
-- mesecon.receptor_get_rules(node) --> Returns the rules of the receptor (mesecon.rules.default if none specified)
-- EFFECTORS
-- mesecon.is_effector(nodename) --> Returns true if nodename is an effector
-- mesecon.is_effector_on(nodename) --> Returns true if nodename is an effector with nodedef.mesecons.effector.action_off
-- mesecon.is_effector_off(nodename) --> Returns true if nodename is an effector with nodedef.mesecons.effector.action_on
-- mesecon.effector_get_rules(node) --> Returns the input rules of the effector (mesecon.rules.default if none specified)
-- SIGNALS
-- mesecon.activate(pos, node, depth) --> Activates the effector node at the specific pos (calls nodedef.mesecons.effector.action_on), higher depths are executed later
-- mesecon.deactivate(pos, node, depth) --> Deactivates the effector node at the specific pos (calls nodedef.mesecons.effector.action_off), higher depths are executed later
-- mesecon.changesignal(pos, node, rulename, newstate, depth) --> Changes the effector node at the specific pos (calls nodedef.mesecons.effector.action_change), higher depths are executed later
-- CONDUCTORS
-- mesecon.is_conductor(nodename) --> Returns true if nodename is a conductor
-- mesecon.is_conductor_on(node --> Returns true if node is a conductor with state = mesecon.state.on
-- mesecon.is_conductor_off(node) --> Returns true if node is a conductor with state = mesecon.state.off
-- mesecon.get_conductor_on(node_off) --> Returns the onstate nodename of the conductor
-- mesecon.get_conductor_off(node_on) --> Returns the offstate nodename of the conductor
-- mesecon.conductor_get_rules(node) --> Returns the input+output rules of a conductor (mesecon.rules.default if none specified)
-- HIGH-LEVEL Internals
-- mesecon.is_power_on(pos) --> Returns true if pos emits power in any way
-- mesecon.is_power_off(pos) --> Returns true if pos does not emit power in any way
-- mesecon.is_powered(pos) --> Returns true if pos is powered by a receptor or a conductor
-- RULES ROTATION helpers
-- mesecon.rotate_rules_right(rules)
-- mesecon.rotate_rules_left(rules)
-- mesecon.rotate_rules_up(rules)
-- mesecon.rotate_rules_down(rules)
-- These functions return rules that have been rotated in the specific direction
-- General
function mesecon.get_effector(nodename)
if minetest.registered_nodes[nodename]
and minetest.registered_nodes[nodename].mesecons
and minetest.registered_nodes[nodename].mesecons.effector then
return minetest.registered_nodes[nodename].mesecons.effector
end
end
function mesecon.get_receptor(nodename)
if minetest.registered_nodes[nodename]
and minetest.registered_nodes[nodename].mesecons
and minetest.registered_nodes[nodename].mesecons.receptor then
return minetest.registered_nodes[nodename].mesecons.receptor
end
end
function mesecon.get_conductor(nodename)
if minetest.registered_nodes[nodename]
and minetest.registered_nodes[nodename].mesecons
and minetest.registered_nodes[nodename].mesecons.conductor then
return minetest.registered_nodes[nodename].mesecons.conductor
end
end
function mesecon.get_any_outputrules(node)
if not node then return nil end
if mesecon.is_conductor(node.name) then
return mesecon.conductor_get_rules(node)
elseif mesecon.is_receptor(node.name) then
return mesecon.receptor_get_rules(node)
end
end
function mesecon.get_any_inputrules(node)
if not node then return nil end
if mesecon.is_conductor(node.name) then
return mesecon.conductor_get_rules(node)
elseif mesecon.is_effector(node.name) then
return mesecon.effector_get_rules(node)
end
end
function mesecon.get_any_rules(node)
return mesecon.mergetable(mesecon.get_any_inputrules(node) or {},
mesecon.get_any_outputrules(node) or {})
end
-- Receptors
-- Nodes that can power mesecons
function mesecon.is_receptor_on(nodename)
local receptor = mesecon.get_receptor(nodename)
if receptor and receptor.state == mesecon.state.on then
return true
end
return false
end
function mesecon.is_receptor_off(nodename)
local receptor = mesecon.get_receptor(nodename)
if receptor and receptor.state == mesecon.state.off then
return true
end
return false
end
function mesecon.is_receptor(nodename)
local receptor = mesecon.get_receptor(nodename)
if receptor then
return true
end
return false
end
function mesecon.receptor_get_rules(node)
local receptor = mesecon.get_receptor(node.name)
if receptor then
local rules = receptor.rules
if type(rules) == 'function' then
return rules(node)
elseif rules then
return rules
end
end
return mesecon.rules.default
end
-- Effectors
-- Nodes that can be powered by mesecons
function mesecon.is_effector_on(nodename)
local effector = mesecon.get_effector(nodename)
if effector and effector.action_off then
return true
end
return false
end
function mesecon.is_effector_off(nodename)
local effector = mesecon.get_effector(nodename)
if effector and effector.action_on then
return true
end
return false
end
function mesecon.is_effector(nodename)
local effector = mesecon.get_effector(nodename)
if effector then
return true
end
return false
end
function mesecon.effector_get_rules(node)
local effector = mesecon.get_effector(node.name)
if effector then
local rules = effector.rules
if type(rules) == 'function' then
return rules(node)
elseif rules then
return rules
end
end
return mesecon.rules.default
end
-- #######################
-- # Signals (effectors) #
-- #######################
-- Activation:
mesecon.queue:add_function("activate", function (pos, rulename)
local node = mesecon.get_node_force(pos)
if not node then return end
local effector = mesecon.get_effector(node.name)
if effector and effector.action_on then
effector.action_on(pos, node, rulename)
end
end)
function mesecon.activate(pos, node, rulename, depth)
if rulename == nil then
for _,rule in ipairs(mesecon.effector_get_rules(node)) do
mesecon.activate(pos, node, rule, depth + 1)
end
return
end
mesecon.queue:add_action(pos, "activate", {rulename}, nil, rulename, 1 / depth)
end
-- Deactivation
mesecon.queue:add_function("deactivate", function (pos, rulename)
local node = mesecon.get_node_force(pos)
if not node then return end
local effector = mesecon.get_effector(node.name)
if effector and effector.action_off then
effector.action_off(pos, node, rulename)
end
end)
function mesecon.deactivate(pos, node, rulename, depth)
if rulename == nil then
for _,rule in ipairs(mesecon.effector_get_rules(node)) do
mesecon.deactivate(pos, node, rule, depth + 1)
end
return
end
mesecon.queue:add_action(pos, "deactivate", {rulename}, nil, rulename, 1 / depth)
end
-- Change
mesecon.queue:add_function("change", function (pos, rulename, changetype)
local node = mesecon.get_node_force(pos)
if not node then return end
local effector = mesecon.get_effector(node.name)
if effector and effector.action_change then
effector.action_change(pos, node, rulename, changetype)
end
end)
function mesecon.changesignal(pos, node, rulename, newstate, depth)
if rulename == nil then
for _,rule in ipairs(mesecon.effector_get_rules(node)) do
mesecon.changesignal(pos, node, rule, newstate, depth + 1)
end
return
end
-- Include "change" in overwritecheck so that it cannot be overwritten
-- by "active" / "deactivate" that will be called upon the node at the same time.
local overwritecheck = {"change", rulename}
mesecon.queue:add_action(pos, "change", {rulename, newstate}, nil, overwritecheck, 1 / depth)
end
-- Conductors
function mesecon.is_conductor_on(node, rulename)
if not node then return false end
local conductor = mesecon.get_conductor(node.name)
if conductor then
if conductor.state then
return conductor.state == mesecon.state.on
end
if conductor.states then
if not rulename then
return mesecon.getstate(node.name, conductor.states) ~= 1
end
local bit = mesecon.rule2bit(rulename, mesecon.conductor_get_rules(node))
local binstate = mesecon.getbinstate(node.name, conductor.states)
return mesecon.get_bit(binstate, bit)
end
end
return false
end
function mesecon.is_conductor_off(node, rulename)
if not node then return false end
local conductor = mesecon.get_conductor(node.name)
if conductor then
if conductor.state then
return conductor.state == mesecon.state.off
end
if conductor.states then
if not rulename then
return mesecon.getstate(node.name, conductor.states) == 1
end
local bit = mesecon.rule2bit(rulename, mesecon.conductor_get_rules(node))
local binstate = mesecon.getbinstate(node.name, conductor.states)
return not mesecon.get_bit(binstate, bit)
end
end
return false
end
function mesecon.is_conductor(nodename)
local conductor = mesecon.get_conductor(nodename)
if conductor then
return true
end
return false
end
function mesecon.get_conductor_on(node_off, rulename)
local conductor = mesecon.get_conductor(node_off.name)
if conductor then
if conductor.onstate then
return conductor.onstate
end
if conductor.states then
local bit = mesecon.rule2bit(rulename, mesecon.conductor_get_rules(node_off))
local binstate = mesecon.getbinstate(node_off.name, conductor.states)
binstate = mesecon.set_bit(binstate, bit, "1")
return conductor.states[tonumber(binstate,2)+1]
end
end
return offstate
end
function mesecon.get_conductor_off(node_on, rulename)
local conductor = mesecon.get_conductor(node_on.name)
if conductor then
if conductor.offstate then
return conductor.offstate
end
if conductor.states then
local bit = mesecon.rule2bit(rulename, mesecon.conductor_get_rules(node_on))
local binstate = mesecon.getbinstate(node_on.name, conductor.states)
binstate = mesecon.set_bit(binstate, bit, "0")
return conductor.states[tonumber(binstate,2)+1]
end
end
return onstate
end
function mesecon.conductor_get_rules(node)
local conductor = mesecon.get_conductor(node.name)
if conductor then
local rules = conductor.rules
if type(rules) == 'function' then
return rules(node)
elseif rules then
return rules
end
end
return mesecon.rules.default
end
-- some more general high-level stuff
function mesecon.is_power_on(pos, rulename)
local node = mesecon.get_node_force(pos)
if node and (mesecon.is_conductor_on(node, rulename) or mesecon.is_receptor_on(node.name)) then
return true
end
return false
end
function mesecon.is_power_off(pos, rulename)
local node = mesecon.get_node_force(pos)
if node and (mesecon.is_conductor_off(node, rulename) or mesecon.is_receptor_off(node.name)) then
return true
end
return false
end
-- Turn off an equipotential section starting at `pos`, which outputs in the direction of `link`.
-- Breadth-first search. Map is abstracted away in a voxelmanip.
-- Follow all all conductor paths replacing conductors that were already
-- looked at, activating / changing all effectors along the way.
function mesecon.turnon(pos, link)
local frontiers = {{pos = pos, link = link}}
local depth = 1
while frontiers[1] do
local f = table.remove(frontiers, 1)
local node = mesecon.get_node_force(f.pos)
if not node then
-- Area does not exist; do nothing
elseif mesecon.is_conductor_off(node, f.link) then
local rules = mesecon.conductor_get_rules(node)
-- Call turnon on neighbors
for _, r in ipairs(mesecon.rule2meta(f.link, rules)) do
local np = vector.add(f.pos, r)
for _, l in ipairs(mesecon.rules_link_rule_all(f.pos, r)) do
table.insert(frontiers, {pos = np, link = l})
end
end
mesecon.swap_node_force(f.pos, mesecon.get_conductor_on(node, f.link))
elseif mesecon.is_effector(node.name) then
mesecon.changesignal(f.pos, node, f.link, mesecon.state.on, depth)
if mesecon.is_effector_off(node.name) then
mesecon.activate(f.pos, node, f.link, depth)
end
end
depth = depth + 1
end
end
-- Turn on an equipotential section starting at `pos`, which outputs in the direction of `link`.
-- Breadth-first search. Map is abstracted away in a voxelmanip.
-- Follow all all conductor paths replacing conductors that were already
-- looked at, deactivating / changing all effectors along the way.
-- In case an onstate receptor is discovered, abort the process by returning false, which will
-- cause `receptor_off` to discard all changes made in the voxelmanip.
-- Contrary to turnon, turnoff has to cache all change and deactivate signals so that they will only
-- be called in the very end when we can be sure that no conductor was found along the path.
--
-- Signal table entry structure:
-- {
-- pos = position of effector,
-- node = node descriptor (name, param1 and param2),
-- link = link the effector is connected to,
-- depth = indicates order in which signals wire fired, higher is later
-- }
function mesecon.turnoff(pos, link)
local frontiers = {{pos = pos, link = link}}
local signals = {}
local depth = 1
while frontiers[1] do
local f = table.remove(frontiers, 1)
local node = mesecon.get_node_force(f.pos)
if not node then
-- Area does not exist; do nothing
elseif mesecon.is_conductor_on(node, f.link) then
local rules = mesecon.conductor_get_rules(node)
for _, r in ipairs(mesecon.rule2meta(f.link, rules)) do
local np = vector.add(f.pos, r)
-- Check if an onstate receptor is connected. If that is the case,
-- abort this turnoff process by returning false. `receptor_off` will
-- discard all the changes that we made in the voxelmanip:
for _, l in ipairs(mesecon.rules_link_rule_all_inverted(f.pos, r)) do
if mesecon.is_receptor_on(mesecon.get_node_force(np).name) then
return false
end
end
-- Call turnoff on neighbors
for _, l in ipairs(mesecon.rules_link_rule_all(f.pos, r)) do
table.insert(frontiers, {pos = np, link = l})
end
end
mesecon.swap_node_force(f.pos, mesecon.get_conductor_off(node, f.link))
elseif mesecon.is_effector(node.name) then
table.insert(signals, {
pos = f.pos,
node = node,
link = f.link,
depth = depth
})
end
depth = depth + 1
end
for _, sig in ipairs(signals) do
mesecon.changesignal(sig.pos, sig.node, sig.link, mesecon.state.off, sig.depth)
if mesecon.is_effector_on(sig.node.name) and not mesecon.is_powered(sig.pos) then
mesecon.deactivate(sig.pos, sig.node, sig.link, sig.depth)
end
end
return true
end
-- Get all linking inputrules of inputnode (effector or conductor) that is connected to
-- outputnode (receptor or conductor) at position `output` and has an output in direction `rule`
function mesecon.rules_link_rule_all(output, rule)
local input = vector.add(output, rule)
local inputnode = mesecon.get_node_force(input)
local inputrules = mesecon.get_any_inputrules(inputnode)
if not inputrules then
return {}
end
local rules = {}
for _, inputrule in ipairs(mesecon.flattenrules(inputrules)) do
-- Check if input accepts from output
if vector.equals(vector.add(input, inputrule), output) then
table.insert(rules, inputrule)
end
end
return rules
end
-- Get all linking outputnodes of outputnode (receptor or conductor) that is connected to
-- inputnode (effector or conductor) at position `input` and has an input in direction `rule`
function mesecon.rules_link_rule_all_inverted(input, rule)
local output = vector.add(input, rule)
local outputnode = mesecon.get_node_force(output)
local outputrules = mesecon.get_any_outputrules(outputnode)
if not outputrules then
return {}
end
local rules = {}
for _, outputrule in ipairs(mesecon.flattenrules(outputrules)) do
if vector.equals(vector.add(output, outputrule), input) then
table.insert(rules, mesecon.invertRule(outputrule))
end
end
return rules
end
function mesecon.is_powered(pos, rule)
local node = mesecon.get_node_force(pos)
local rules = mesecon.get_any_inputrules(node)
if not rules then return false end
-- List of nodes that send out power to pos
local sourcepos = {}
if not rule then
for _, rule in ipairs(mesecon.flattenrules(rules)) do
local rulenames = mesecon.rules_link_rule_all_inverted(pos, rule)
for _, rname in ipairs(rulenames) do
local np = vector.add(pos, rname)
local nn = mesecon.get_node_force(np)
if (mesecon.is_conductor_on(nn, mesecon.invertRule(rname))
or mesecon.is_receptor_on(nn.name)) then
table.insert(sourcepos, np)
end
end
end
else
local rulenames = mesecon.rules_link_rule_all_inverted(pos, rule)
for _, rname in ipairs(rulenames) do
local np = vector.add(pos, rname)
local nn = mesecon.get_node_force(np)
if (mesecon.is_conductor_on (nn, mesecon.invertRule(rname))
or mesecon.is_receptor_on (nn.name)) then
table.insert(sourcepos, np)
end
end
end
-- Return FALSE if not powered, return list of sources if is powered
if (#sourcepos == 0) then return false
else return sourcepos end
end
--Rules rotation Functions:
function mesecon.rotate_rules_right(rules)
local nr = {}
for i, rule in ipairs(rules) do
table.insert(nr, {
x = -rule.z,
y = rule.y,
z = rule.x,
name = rule.name})
end
return nr
end
function mesecon.rotate_rules_left(rules)
local nr = {}
for i, rule in ipairs(rules) do
table.insert(nr, {
x = rule.z,
y = rule.y,
z = -rule.x,
name = rule.name})
end
return nr
end
function mesecon.rotate_rules_down(rules)
local nr = {}
for i, rule in ipairs(rules) do
table.insert(nr, {
x = -rule.y,
y = rule.x,
z = rule.z,
name = rule.name})
end
return nr
end
function mesecon.rotate_rules_up(rules)
local nr = {}
for i, rule in ipairs(rules) do
table.insert(nr, {
x = rule.y,
y = -rule.x,
z = rule.z,
name = rule.name})
end
return nr
end
| gpl-3.0 |
mercury233/ygopro-scripts | c32305461.lua | 3 | 2128 | --占い魔女 エンちゃん
function c32305461.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(32305461,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_DRAW)
e1:SetCountLimit(1,32305461)
e1:SetCost(c32305461.spcost)
e1:SetTarget(c32305461.sptg)
e1:SetOperation(c32305461.spop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(32305461,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCountLimit(1,32305462)
e2:SetCondition(c32305461.descon)
e2:SetTarget(c32305461.destg)
e2:SetOperation(c32305461.desop)
c:RegisterEffect(e2)
end
function c32305461.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not e:GetHandler():IsPublic() end
end
function c32305461.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c32305461.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
function c32305461.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_HAND)
end
function c32305461.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsFacedown() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFacedown,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsFacedown,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c32305461.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c28692962.lua | 2 | 3859 | --紫宵の機界騎士
function c28692962.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,28692962+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c28692962.hspcon)
e1:SetValue(c28692962.hspval)
c:RegisterEffect(e1)
--banish & search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(28692962,0))
e2:SetCategory(CATEGORY_REMOVE+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,28692963)
e2:SetHintTiming(0,TIMING_END_PHASE)
e2:SetTarget(c28692962.thtg)
e2:SetOperation(c28692962.thop)
c:RegisterEffect(e2)
end
function c28692962.cfilter(c)
return c:GetColumnGroupCount()>0
end
function c28692962.hspcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
local zone=0
local lg=Duel.GetMatchingGroup(c28692962.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
for tc in aux.Next(lg) do
zone=bit.bor(zone,tc:GetColumnZone(LOCATION_MZONE,tp))
end
return Duel.GetLocationCount(tp,LOCATION_MZONE,tp,LOCATION_REASON_TOFIELD,zone)>0
end
function c28692962.hspval(e,c)
local tp=c:GetControler()
local zone=0
local lg=Duel.GetMatchingGroup(c28692962.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
for tc in aux.Next(lg) do
zone=bit.bor(zone,tc:GetColumnZone(LOCATION_MZONE,tp))
end
return 0,zone
end
function c28692962.rmfilter(c)
return c:IsFaceup() and c:IsSetCard(0x10c) and c:IsAbleToRemove()
end
function c28692962.thfilter(c)
return c:IsSetCard(0x10c) and c:IsType(TYPE_MONSTER) and not c:IsCode(28692962) and c:IsAbleToHand()
end
function c28692962.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c28692962.rmfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c28692962.rmfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(c28692962.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c28692962.rmfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c28692962.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Remove(tc,0,REASON_EFFECT+REASON_TEMPORARY)~=0
and tc:IsLocation(LOCATION_REMOVED) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(28692962,1))
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetLabelObject(tc)
e1:SetCountLimit(1)
e1:SetCondition(c28692962.retcon)
e1:SetOperation(c28692962.retop)
if Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()<=PHASE_STANDBY then
e1:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,2)
e1:SetValue(Duel.GetTurnCount())
tc:RegisterFlagEffect(28692962,RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,0,2)
else
e1:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN)
e1:SetValue(0)
tc:RegisterFlagEffect(28692962,RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,0,1)
end
Duel.RegisterEffect(e1,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c28692962.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
end
function c28692962.retcon(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetTurnPlayer()~=tp or Duel.GetTurnCount()==e:GetValue() then return false end
return e:GetLabelObject():GetFlagEffect(28692962)~=0
end
function c28692962.retop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
Duel.ReturnToField(tc)
end
| gpl-2.0 |
qq779089973/my_openwrt_mod | luci/libs/lucid-rpc/luasrc/lucid/rpc/server.lua | 52 | 8197 | --[[
LuCI - Lua Development Framework
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]
local ipairs, pairs = ipairs, pairs
local tostring, tonumber = tostring, tonumber
local pcall, assert, type, unpack = pcall, assert, type, unpack
local nixio = require "nixio"
local json = require "luci.json"
local util = require "luci.util"
local table = require "table"
local ltn12 = require "luci.ltn12"
--- RPC daemom.
-- @cstyle instance
module "luci.lucid.rpc.server"
RQLIMIT = 32 * nixio.const.buffersize
VERSION = "1.0"
ERRNO_PARSE = -32700
ERRNO_INVALID = -32600
ERRNO_UNKNOWN = -32001
ERRNO_TIMEOUT = -32000
ERRNO_NOTFOUND = -32601
ERRNO_NOACCESS = -32002
ERRNO_INTERNAL = -32603
ERRNO_NOSUPPORT = -32003
ERRMSG = {
[ERRNO_PARSE] = "Parse error.",
[ERRNO_INVALID] = "Invalid request.",
[ERRNO_TIMEOUT] = "Connection timeout.",
[ERRNO_UNKNOWN] = "Unknown error.",
[ERRNO_NOTFOUND] = "Method not found.",
[ERRNO_NOACCESS] = "Access denied.",
[ERRNO_INTERNAL] = "Internal error.",
[ERRNO_NOSUPPORT] = "Operation not supported."
}
--- Create an RPC method wrapper.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
Method = util.class()
--- Create an extended wrapped RPC method.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
function Method.extended(...)
local m = Method(...)
m.call = m.xcall
return m
end
function Method.__init__(self, method, description)
self.description = description
self.method = method
end
--- Extended call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.xcall(self, session, argv)
return self.method(session, unpack(argv))
end
--- Standard call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.call(self, session, argv)
return self.method(unpack(argv))
end
--- Process a given request and create a JSON response.
-- @param session Session storage
-- @param request Requested method
-- @param argv Request parameters
function Method.process(self, session, request, argv)
local stat, result = pcall(self.call, self, session, argv)
if stat then
return { result=result }
else
return { error={
code=ERRNO_UNKNOWN,
message=ERRMSG[ERRNO_UNKNOWN],
data=result
} }
end
end
-- Remap IPv6-IPv4-compatibility addresses to IPv4 addresses
local function remapipv6(adr)
local map = "::ffff:"
if adr:sub(1, #map) == map then
return adr:sub(#map+1)
else
return adr
end
end
--- Create an RPC module.
-- @class function
-- @param description Method description
-- @return RPC module
Module = util.class()
function Module.__init__(self, description)
self.description = description
self.handler = {}
end
--- Add a handler.
-- @param k key
-- @param v handler
function Module.add(self, k, v)
self.handler[k] = v
end
--- Add an access restriction.
-- @param restriction Restriction specification
function Module.restrict(self, restriction)
if not self.restrictions then
self.restrictions = {restriction}
else
self.restrictions[#self.restrictions+1] = restriction
end
end
--- Enforce access restrictions.
-- @param request Request object
-- @return nil or HTTP statuscode, table of headers, response source
function Module.checkrestricted(self, session, request, argv)
if not self.restrictions then
return
end
for _, r in ipairs(self.restrictions) do
local stat = true
if stat and r.interface then -- Interface restriction
if not session.localif then
for _, v in ipairs(session.env.interfaces) do
if v.addr == session.localaddr then
session.localif = v.name
break
end
end
end
if r.interface ~= session.localif then
stat = false
end
end
if stat and r.user and session.user ~= r.user then -- User restriction
stat = false
end
if stat then
return
end
end
return {error={code=ERRNO_NOACCESS, message=ERRMSG[ERRNO_NOACCESS]}}
end
--- Register a handler, submodule or function.
-- @param m entity
-- @param descr description
-- @return Module (self)
function Module.register(self, m, descr)
descr = descr or {}
for k, v in pairs(m) do
if util.instanceof(v, Method) then
self.handler[k] = v
elseif type(v) == "table" then
self.handler[k] = Module()
self.handler[k]:register(v, descr[k])
elseif type(v) == "function" then
self.handler[k] = Method(v, descr[k])
end
end
return self
end
--- Process a request.
-- @param session Session storage
-- @param request Request object
-- @param argv Request parameters
-- @return JSON response object
function Module.process(self, session, request, argv)
local first, last = request:match("^([^.]+).?(.*)$")
local stat = self:checkrestricted(session, request, argv)
if stat then -- Access Denied
return stat
end
local hndl = first and self.handler[first]
if not hndl then
return {error={code=ERRNO_NOTFOUND, message=ERRMSG[ERRNO_NOTFOUND]}}
end
session.chain[#session.chain+1] = self
return hndl:process(session, last, argv)
end
--- Create a server object.
-- @class function
-- @param root Root module
-- @return Server object
Server = util.class()
function Server.__init__(self, root)
self.root = root
end
--- Get the associated root module.
-- @return Root module
function Server.get_root(self)
return self.root
end
--- Set a new root module.
-- @param root Root module
function Server.set_root(self, root)
self.root = root
end
--- Create a JSON reply.
-- @param jsonrpc JSON-RPC version
-- @param id Message id
-- @param res Result
-- @param err Error
-- @reutrn JSON response source
function Server.reply(self, jsonrpc, id, res, err)
id = id or json.null
-- 1.0 compatibility
if jsonrpc ~= "2.0" then
jsonrpc = nil
res = res or json.null
err = err or json.null
end
return json.Encoder(
{id=id, result=res, error=err, jsonrpc=jsonrpc}, BUFSIZE
):source()
end
--- Handle a new client connection.
-- @param client client socket
-- @param env superserver environment
function Server.process(self, client, env)
local decoder
local sinkout = client:sink()
client:setopt("socket", "sndtimeo", 90)
client:setopt("socket", "rcvtimeo", 90)
local close = false
local session = {server = self, chain = {}, client = client, env = env,
localaddr = remapipv6(client:getsockname())}
local req, stat, response, result, cb
repeat
local oldchunk = decoder and decoder.chunk
decoder = json.ActiveDecoder(client:blocksource(nil, RQLIMIT))
decoder.chunk = oldchunk
result, response, cb = nil, nil, nil
-- Read one request
stat, req = pcall(decoder.get, decoder)
if stat then
if type(req) == "table" and type(req.method) == "string"
and (not req.params or type(req.params) == "table") then
req.params = req.params or {}
result, cb = self.root:process(session, req.method, req.params)
if type(result) == "table" then
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id,
result.result, result.error)
end
close = result.close
else
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id, nil,
{code=ERRNO_INTERNAL, message=ERRMSG[ERRNO_INTERNAL]})
end
end
else
response = self:reply(req.jsonrpc, req.id,
nil, {code=ERRNO_INVALID, message=ERRMSG[ERRNO_INVALID]})
end
else
if nixio.errno() ~= nixio.const.EAGAIN then
response = self:reply("2.0", nil,
nil, {code=ERRNO_PARSE, message=ERRMSG[ERRNO_PARSE]})
--[[else
response = self:reply("2.0", nil,
nil, {code=ERRNO_TIMEOUT, message=ERRMSG_TIMEOUT})]]
end
close = true
end
if response then
ltn12.pump.all(response, sinkout)
end
if cb then
close = cb(client, session, self) or close
end
until close
client:shutdown()
client:close()
end
| mit |
mercury233/ygopro-scripts | c975299.lua | 2 | 3704 | --巨大要塞ゼロス
function c975299.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetOperation(c975299.activate)
c:RegisterEffect(e1)
--atk/def up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_FZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x15))
e2:SetValue(500)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e3)
--indes
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetRange(LOCATION_FZONE)
e4:SetTargetRange(LOCATION_MZONE,0)
e4:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x15))
e4:SetValue(aux.indoval)
c:RegisterEffect(e4)
--cannot be target
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e5:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e5:SetRange(LOCATION_FZONE)
e5:SetTargetRange(LOCATION_MZONE,0)
e5:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x15))
e5:SetValue(aux.tgoval)
c:RegisterEffect(e5)
--spsummon
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(975299,1))
e6:SetCategory(CATEGORY_SPECIAL_SUMMON)
e6:SetType(EFFECT_TYPE_IGNITION)
e6:SetRange(LOCATION_FZONE)
e6:SetCountLimit(1)
e6:SetTarget(c975299.sptg)
e6:SetOperation(c975299.spop)
c:RegisterEffect(e6)
--counter
local e7=Effect.CreateEffect(c)
e7:SetDescription(aux.Stringid(975299,2))
e7:SetCategory(CATEGORY_COUNTER)
e7:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e7:SetCode(EVENT_SUMMON_SUCCESS)
e7:SetRange(LOCATION_FZONE)
e7:SetCondition(c975299.ctcon)
e7:SetTarget(c975299.cttg)
e7:SetOperation(c975299.ctop)
c:RegisterEffect(e7)
local e8=e7:Clone()
e8:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e8)
end
function c975299.thfilter(c)
return c:IsCode(66947414) and c:IsAbleToHand()
end
function c975299.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c975299.thfilter,tp,LOCATION_DECK,0,nil)
if g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(975299,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local sg=g:Select(tp,1,1,nil)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
function c975299.spfilter(c,e,tp)
return c:IsSetCard(0x15) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c975299.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c975299.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c975299.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c975299.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c975299.ctfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x15) and c:IsControler(tp)
end
function c975299.ctcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c975299.ctfilter,1,nil,tp)
end
function c975299.cttg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local ec=eg:FilterCount(c975299.ctfilter,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,ec,0,0x1f)
end
function c975299.ctop(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c975299.ctfilter,nil,tp)
local tc=g:GetFirst()
while tc do
tc:AddCounter(0x1f,1)
tc=g:GetNext()
end
end
| gpl-2.0 |
linushsao/marsu_game-linus-v0.2 | mods/technical/mesecons/mesecons_blinkyplant/init.lua | 8 | 1381 | -- The BLINKY_PLANT
local toggle_timer = function (pos)
local timer = minetest.get_node_timer(pos)
if timer:is_started() then
timer:stop()
else
timer:start(mesecon.setting("blinky_plant_interval", 3))
end
end
local on_timer = function (pos)
local node = minetest.get_node(pos)
if(mesecon.flipstate(pos, node) == "on") then
mesecon.receptor_on(pos)
else
mesecon.receptor_off(pos)
end
toggle_timer(pos)
end
mesecon.register_node("mesecons_blinkyplant:blinky_plant", {
description="Blinky Plant",
drawtype = "plantlike",
inventory_image = "jeija_blinky_plant_off.png",
paramtype = "light",
walkable = false,
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, -0.5+0.7, 0.3},
},
on_timer = on_timer,
on_rightclick = toggle_timer,
on_construct = toggle_timer
},{
tiles = {"jeija_blinky_plant_off.png"},
groups = {dig_immediate=3},
mesecons = {receptor = { state = mesecon.state.off }}
},{
tiles = {"jeija_blinky_plant_on.png"},
groups = {dig_immediate=3, not_in_creative_inventory=1},
mesecons = {receptor = { state = mesecon.state.on }}
})
minetest.register_craft({
output = "mesecons_blinkyplant:blinky_plant_off 1",
recipe = { {"","group:mesecon_conductor_craftable",""},
{"","group:mesecon_conductor_craftable",""},
{"group:sapling","group:sapling","group:sapling"}}
})
| gpl-3.0 |
terminar/lua-handlers | perf/zmq/local_lat.lua | 2 | 1863 | -- Copyright (c) 2010 by Robert G. Jakabosky <bobby@neoawareness.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, replish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local format = string.format
local function printf(fmt, ...)
print(format(fmt, ...))
end
if #arg ~= 3 then
printf("usage: %s <bind-to> <message-size> <roundtrip-count>", arg[0])
os.exit()
end
local bind_to = arg[1]
local message_size = tonumber(arg[2])
local roundtrip_count = tonumber(arg[3])
local zmq = require'handler.zmq'
local ev = require'ev'
local loop = ev.Loop.default
local ctx = zmq.init(loop, 1)
local i = 0
-- define request handler
local function handle_msg(sock, data)
sock:send(data)
i = i + 1
if i == roundtrip_count then
loop:unloop()
end
end
-- create response worker
local zrep = ctx:rep(handle_msg)
zrep.recv_max = 1000
zrep:bind(bind_to)
loop:loop()
zrep:close()
ctx:term()
| mit |
qq779089973/my_openwrt_mod | luci/applications/luci-statistics/luasrc/statistics/rrdtool.lua | 69 | 15320 | --[[
Luci statistics - rrdtool interface library / diagram model interpreter
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.statistics.rrdtool", package.seeall)
require("luci.statistics.datatree")
require("luci.statistics.rrdtool.colors")
require("luci.statistics.i18n")
require("luci.model.uci")
require("luci.util")
require("luci.sys")
local fs = require "nixio.fs"
Graph = luci.util.class()
function Graph.__init__( self, timespan, opts )
opts = opts or { }
local uci = luci.model.uci.cursor()
local sections = uci:get_all( "luci_statistics" )
-- options
opts.timespan = timespan or sections.rrdtool.default_timespan or 900
opts.rrasingle = opts.rrasingle or ( sections.collectd_rrdtool.RRASingle == "1" )
opts.host = opts.host or sections.collectd.Hostname or luci.sys.hostname()
opts.width = opts.width or sections.rrdtool.image_width or 400
opts.rrdpath = opts.rrdpath or sections.collectd_rrdtool.DataDir or "/tmp/rrd"
opts.imgpath = opts.imgpath or sections.rrdtool.image_path or "/tmp/rrdimg"
opts.rrdpath = opts.rrdpath:gsub("/$","")
opts.imgpath = opts.imgpath:gsub("/$","")
-- helper classes
self.colors = luci.statistics.rrdtool.colors.Instance()
self.tree = luci.statistics.datatree.Instance(opts.host)
self.i18n = luci.statistics.i18n.Instance( self )
-- rrdtool default args
self.args = {
"-a", "PNG",
"-s", "NOW-" .. opts.timespan,
"-w", opts.width
}
-- store options
self.opts = opts
end
function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance )
local t = self.opts.host .. "/" .. plugin
if type(plugin_instance) == "string" and plugin_instance:len() > 0 then
t = t .. "-" .. plugin_instance
end
t = t .. "/" .. dtype
if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
t = t .. "-" .. dtype_instance
end
return t
end
function Graph.mkrrdpath( self, ... )
return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
end
function Graph.mkpngpath( self, ... )
return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
end
function Graph.strippngpath( self, path )
return path:sub( self.opts.imgpath:len() + 2 )
end
function Graph._forcelol( self, list )
if type(list[1]) ~= "table" then
return( { list } )
end
return( list )
end
function Graph._rrdtool( self, def, rrd )
-- prepare directory
local dir = def[1]:gsub("/[^/]+$","")
fs.mkdirr( dir )
-- construct commandline
local cmdline = "rrdtool graph"
-- copy default arguments to def stack
for i, opt in ipairs(self.args) do
table.insert( def, 1 + i, opt )
end
-- construct commandline from def stack
for i, opt in ipairs(def) do
opt = opt .. "" -- force string
if rrd then
opt = opt:gsub( "{file}", rrd )
end
if opt:match("[^%w]") then
cmdline = cmdline .. " '" .. opt .. "'"
else
cmdline = cmdline .. " " .. opt
end
end
-- execute rrdtool
local rrdtool = io.popen( cmdline )
rrdtool:close()
end
function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
-- generated graph defs
local defs = { }
-- internal state variables
local _args = { }
local _sources = { }
local _stack_neg = { }
local _stack_pos = { }
local _longest_name = 0
local _has_totals = false
-- some convenient aliases
local _ti = table.insert
local _sf = string.format
-- local helper: append a string.format() formatted string to given table
function _tif( list, fmt, ... )
table.insert( list, string.format( fmt, ... ) )
end
-- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
function __def(source)
local inst = source.sname
local rrd = source.rrd
local ds = source.ds
if not ds or ds:len() == 0 then ds = "value" end
_tif( _args, "DEF:%s_avg_raw=%s:%s:AVERAGE", inst, rrd, ds )
_tif( _args, "CDEF:%s_avg=%s_avg_raw,%s", inst, inst, source.transform_rpn )
if not self.opts.rrasingle then
_tif( _args, "DEF:%s_min_raw=%s:%s:MIN", inst, rrd, ds )
_tif( _args, "CDEF:%s_min=%s_min_raw,%s", inst, inst, source.transform_rpn )
_tif( _args, "DEF:%s_max_raw=%s:%s:MAX", inst, rrd, ds )
_tif( _args, "CDEF:%s_max=%s_max_raw,%s", inst, inst, source.transform_rpn )
end
_tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
end
-- local helper: create cdefs depending on source options like flip and overlay
function __cdef(source)
local prev
-- find previous source, choose stack depending on flip state
if source.flip then
prev = _stack_neg[#_stack_neg]
else
prev = _stack_pos[#_stack_pos]
end
-- is first source in stack or overlay source: source_stk = source_nnl
if not prev or source.overlay then
-- create cdef statement for cumulative stack (no NaNs) and also
-- for display (preserving NaN where no points should be displayed)
_tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
_tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname )
-- is subsequent source without overlay: source_stk = source_nnl + previous_stk
else
-- create cdef statement
_tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
_tif( _args, "CDEF:%s_plot=%s_avg,%s_stk,+", source.sname, source.sname, prev )
end
-- create multiply by minus one cdef if flip is enabled
if source.flip then
-- create cdef statement: source_stk = source_stk * -1
_tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
-- push to negative stack if overlay is disabled
if not source.overlay then
_ti( _stack_neg, source.sname )
end
-- no flipping, push to positive stack if overlay is disabled
elseif not source.overlay then
-- push to positive stack
_ti( _stack_pos, source.sname )
end
-- calculate total amount of data if requested
if source.total then
_tif( _args,
"CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
source.sname, source.sname, source.sname
)
_tif( _args,
"CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
source.sname, source.sname, source.sname
)
end
end
-- local helper: create cdefs required for calculating total values
function __cdef_totals()
if _has_totals then
_tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname )
_ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" )
_ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
end
end
-- local helper: create line and area statements
function __line(source)
local line_color
local area_color
local legend
local var
-- find colors: try source, then opts.colors; fall back to random color
if type(source.color) == "string" then
line_color = source.color
area_color = self.colors:from_string( line_color )
elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
line_color = opts.colors[source.name:gsub("[^%w]","_")]
area_color = self.colors:from_string( line_color )
else
area_color = self.colors:random()
line_color = self.colors:to_string( area_color )
end
-- derive area background color from line color
area_color = self.colors:to_string( self.colors:faded( area_color ) )
-- choose source_plot or source_neg variable depending on flip state
if source.flip then
var = "neg"
else
var = "plot"
end
-- create legend
legend = _sf( "%-" .. _longest_name .. "s", source.title )
-- create area if not disabled
if not source.noarea then
_tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
end
-- create line1 statement
_tif( _args, "LINE%d:%s_%s#%s:%s",
source.noarea and 2 or 1,
source.sname, var, line_color, legend )
end
-- local helper: create gprint statements
function __gprint(source)
local numfmt = opts.number_format or "%6.1lf"
local totfmt = opts.totals_format or "%5.1lf%s"
-- don't include MIN if rrasingle is enabled
if not self.opts.rrasingle then
_tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
end
-- always include AVERAGE
_tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
-- don't include MAX if rrasingle is enabled
if not self.opts.rrasingle then
_tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
end
-- include total count if requested else include LAST
if source.total then
_tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
else
_tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
end
end
--
-- find all data sources
--
-- find data types
local data_types
if dtype then
data_types = { dtype }
else
data_types = opts.data.types or { }
end
if not ( dtype or opts.data.types ) then
if opts.data.instances then
for k, v in pairs(opts.data.instances) do
_ti( data_types, k )
end
elseif opts.data.sources then
for k, v in pairs(opts.data.sources) do
_ti( data_types, k )
end
end
end
-- iterate over data types
for i, dtype in ipairs(data_types) do
-- find instances
local data_instances
if not opts.per_instance then
if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
data_instances = opts.data.instances[dtype]
else
data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
end
end
if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
-- iterate over data instances
for i, dinst in ipairs(data_instances) do
-- construct combined data type / instance name
local dname = dtype
if dinst:len() > 0 then
dname = dname .. "_" .. dinst
end
-- find sources
local data_sources = { "value" }
if type(opts.data.sources) == "table" then
if type(opts.data.sources[dname]) == "table" then
data_sources = opts.data.sources[dname]
elseif type(opts.data.sources[dtype]) == "table" then
data_sources = opts.data.sources[dtype]
end
end
-- iterate over data sources
for i, dsource in ipairs(data_sources) do
local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
local altname = dtype .. "__" .. dsource
--assert(dtype ~= "ping", dsname .. " or " .. altname)
-- find datasource options
local dopts = { }
if type(opts.data.options) == "table" then
if type(opts.data.options[dsname]) == "table" then
dopts = opts.data.options[dsname]
elseif type(opts.data.options[altname]) == "table" then
dopts = opts.data.options[altname]
elseif type(opts.data.options[dname]) == "table" then
dopts = opts.data.options[dname]
elseif type(opts.data.options[dtype]) == "table" then
dopts = opts.data.options[dtype]
end
end
-- store values
_ti( _sources, {
rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
color = dopts.color or self.colors:to_string( self.colors:random() ),
flip = dopts.flip or false,
total = dopts.total or false,
overlay = dopts.overlay or false,
transform_rpn = dopts.transform_rpn or "0,+",
noarea = dopts.noarea or false,
title = dopts.title or nil,
ds = dsource,
type = dtype,
instance = dinst,
index = #_sources + 1,
sname = ( #_sources + 1 ) .. dtype
} )
-- generate datasource title
_sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
-- find longest name ...
if _sources[#_sources].title:len() > _longest_name then
_longest_name = _sources[#_sources].title:len()
end
-- has totals?
if _sources[#_sources].total then
_has_totals = true
end
end
end
end
--
-- construct diagrams
--
-- if per_instance is enabled then find all instances from the first datasource in diagram
-- if per_instance is disabled then use an empty pseudo instance and use model provided values
local instances = { "" }
if opts.per_instance then
instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
end
-- iterate over instances
for i, instance in ipairs(instances) do
-- store title and vlabel
_ti( _args, "-t" )
_ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
_ti( _args, "-v" )
_ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
if opts.y_max then
_ti ( _args, "-u" )
_ti ( _args, opts.y_max )
end
if opts.y_min then
_ti ( _args, "-l" )
_ti ( _args, opts.y_min )
end
if opts.units_exponent then
_ti ( _args, "-X" )
_ti ( _args, opts.units_exponent )
end
-- store additional rrd options
if opts.rrdopts then
for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
end
-- create DEF statements for each instance
for i, source in ipairs(_sources) do
-- fixup properties for per instance mode...
if opts.per_instance then
source.instance = instance
source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
end
__def( source )
end
-- create CDEF required for calculating totals
__cdef_totals()
-- create CDEF statements for each instance in reversed order
for i, source in ipairs(_sources) do
__cdef( _sources[1 + #_sources - i] )
end
-- create LINE1, AREA and GPRINT statements for each instance
for i, source in ipairs(_sources) do
__line( source )
__gprint( source )
end
-- prepend image path to arg stack
_ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
-- push arg stack to definition list
_ti( defs, _args )
-- reset stacks
_args = { }
_stack_pos = { }
_stack_neg = { }
end
return defs
end
function Graph.render( self, plugin, plugin_instance, is_index )
dtype_instances = dtype_instances or { "" }
local pngs = { }
-- check for a whole graph handler
local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
local stat, def = pcall( require, plugin_def )
if stat and def and type(def.rrdargs) == "function" then
-- temporary image matrix
local _images = { }
-- get diagram definitions
for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
if not is_index or not opts.detail then
_images[i] = { }
-- get diagram definition instances
local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
-- render all diagrams
for j, def in ipairs( diagrams ) do
-- remember image
_images[i][j] = def[1]
-- exec
self:_rrdtool( def )
end
end
end
-- remember images - XXX: fixme (will cause probs with asymmetric data)
for y = 1, #_images[1] do
for x = 1, #_images do
table.insert( pngs, _images[x][y] )
end
end
end
return pngs
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.