Jump to content

Help! stuck with errors Recipe modding


Recommended Posts

Hi guys! Im trying to modify and already existing mod to work with another mod. ("This is Lucy" and "Hero in the Dark"). although i do indeed have it working in a way, i was wonder if i could make it so that Dont start would check for if an instance of This is Lucy is created and, if so, delete the recipe for This is lucy that i created. then again, if there is NO instance of Lucy created, then it would enable the recipe for only 1 usage before disabling the recipe again. I did this because the way that Hero in the dark works, doesnt prove the 'for' statement true when checking if the player prefab is 'woodie' in order to Automatically place the axe in the inventory on startup for its modded characters(knight, paladin, ect).... so, i had to make a recipe that would make the axe accessible to those characters without getting rid of the check for woodie AND eliminating the recipe so i wont be "tempted" to create multiple lucy axes for the sake of convenience. plus i feel that their should only be 1 lucy. :grin:... is their a way to make this a reality?here is the code for both the mainmod.lua and the prefab.lua

 

    -- locals -----------------------------------
    local STRINGS            = GLOBAL.STRINGS
    local TUNING            = GLOBAL.TUNING
    local package         = GLOBAL.package
    ---------------------------------------------

    Assets =
    {
    Asset("IMAGE", "icon.tex"),
    Asset("ATLAS", "icon.xml"),
    }
    package.path = "mods\\This Is Lucy 1.73.5 -giants-\\scripts\\?.lua;"..package.path
    -- version 1.73
    versnr = "1.73.5"
    STRINGS.THISISLUCY_VERSION = versnr
    update = "'Reign of Giants'"
    placeholder = "\n******************************************************\n******************************************************\n"
    print("\n",placeholder,"\n","\t","This Is Lucy","\n","\t","Version: ",versnr,"\n","\t","Update: ",update,"\n\n","\t","DontStarver (2014)","\n",placeholder)
    ---------------------------------------------
    -- strings
    GLOBAL.STRINGS.THISISLUCY_NAMES = {"This Is Lucy", ".....", "..a horrirble..axe", "????", "    "}
    GLOBAL.STRINGS.NAMES.THISISLUCY = "This Is Lucy"
    GLOBAL.STRINGS.RECIPE_DESC.THISISLUCY = "Axe with a \nmysterious magical effect..."
    GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.THISISLUCY = "Axe with a \nmysterious magical effect..."
    -- TUNINGS
    TUNING.THISISLUCY_DAMAGE = 10
    TUNING.THISISLUCY_DECREASE_WALKSPEED = 4
    TUNING.THISISLUCY_DECREASE_RUNSPEED = 6
    TUNING.THISISLUCY_DECREASE_WALKCREEPSPEED = 0.85
    TUNING.THISISLUCY_DECREASE_WALKSPEEDMULT = 0.8
    TUNING.THISISLUCY_DECREASE_WALKFASTMULT = 1.3
    TUNING.THISISLUCY_DECREASE_WALKSLOWMULT = 0.6
    TUNING.THISISLUCY_DECREASE_WALKGROUNDMULT = 1.0
    TUNING.THISISLUCY_CROP_TIME = 5
    ---------------------------------------------
    PrefabFiles = {"thisislucy"}
    ---------------------------------------------

    local thisislucy = GLOBAL.Recipe("thisislucy", {GLOBAL.Ingredient("darkpetals", 20), GLOBAL.Ingredient("nightmarefuel", 5), GLOBAL.Ingredient("livinglog", 5), GLOBAL.Ingredient("boards", 15)}, GLOBAL.RECIPETABS.TOOLS, GLOBAL.TECH.NONE, placeholder)
--    local thisislucy = GLOBAL.Recipe("thisislucy", {GLOBAL.Ingredient("petals", 1)}, GLOBAL.RECIPETABS.TOOLS, GLOBAL.TECH.NONE)
    thisislucy.atlas = "images/inventoryimages/thisislucy.xml"

local function lucyloader(inst)
    local st_inv = inst.components.inventory.starting_inventory
    if (st_inv) then
        table.insert(st_inv, "thisislucy")        
    else
        inst.components.inventory.starting_inventory = {"thisislucy"}
        Global.Recipe.thisislucy:Cancel()
        
    end    
end
for k,prefab in ipairs(GLOBAL.MODCHARACTERLIST) do
        AddPrefabPostInit(prefab, lucyloader)
end
for k,prefab in ipairs(CHARACTERLIST) do
    if prefab ~= "woodie" then
        AddPrefabPostInit(prefab, lucyloader)
    end
end

  local assets =
{
    Asset("ANIM", "anim/lucy_axe.zip"),
    Asset("ANIM", "anim/swap_lucy_axe.zip"),
    Asset("ATLAS", "images/inventoryimages/thisislucy.xml"),
}
prefabs = {
    "explode_small",
    "sparks",
}

local lightfade_colours =
{
    {128/255,255/255,255/255},
    {254/255,217/255,129/255},
    {192/255,192/255,192/255},
    {240/255,240/255,240/255},
    {157/255,213/255,43/255},
    {180/255,180/255,231/255},
}

    local player = GetPlayer()
    local owner = GetPlayer()

    -- dodelta_tasks
    local SEGTIME = TUNING.SEG_TIME                    --30
    local SEGTIME_HALF = 15
    local SEGTIME_SHORT = 7.5
    
    -- delta, time values - dodelta_tasks
    local DODELTA_RAND = -math.random(1, 5)
    local HEALTH_DODELTA = -1    
    local HUNGER_DODELTA = -5
    local SANITY_DODELTA = -10
    
    local TIME = -3
    local SANITY_TIME = -121
    --local TIMETOABSORB = math.random(1, 10)
    --local up_timer = 121
    --local down_timer = -121
    
    local ON = true
    local OFF = false

-- health, hunger, sanity
local function dodelta_tasks(player)
    local player = GetPlayer()
    if player.components.hunger then
        player.SoundEmitter:PlaySound("dontstarve/rain/thunder_close", "thunder_far_2")
        player.SoundEmitter:SetParameter("thunder_far_2", "intensity", 0.01)
        player.components.hunger:DoDelta(HUNGER_DODELTA, TIME)
    end
    
    if player.components.sanity then
        player.components.sanity:DoDelta(SANITY_DODELTA, SANITY_TIME)
    end
    
    if player.components.health and not player.components.health:IsDead() then
        player.components.health.invincible = OFF
        player.components.health:DoDelta(HEALTH_DODELTA, TIME, nil, true)
    end
end

local function chopupdate(inst)
    if inst.components.tool and inst:HasTag("thisislucy") then
        GetClock():DoLightningLighting(1)
        inst.components.tool:SetAction(ACTIONS.CHOP, math.random(3, 9) )
    end
end

local function updatedamage(inst, owner, weapon)
    local owner = GetPlayer()
    local weapon = inst.components.weapon
    
    --if inst.growfntask then
    --    inst.growfntask:Cancel()
    --    inst.growfntask = nil
    --end
    
    if weapon and inst.components.inventoryitem then
        GetClock():DoLightningLighting(1)
        
        --#####################################################
        -- disabled >> 1.73
        --owner.SoundEmitter:PlaySound("dontstarve/creatures/leif/livinglog_burn", "livinglog_burn")
        --owner.SoundEmitter:SetParameter("livinglog_burn", "intensity", 0.01)
        --#####################################################
        
        inst.components.weapon:SetDamage(math.random()*12)
    end
    ---------------------------------------------
    inst.growfntask = inst:DoTaskInTime(121, function()
        GetClock():DoLightningLighting(121)
        GetSeasonManager():LightningWhenRaining()
        
        local mathrange = math.random(5, 15)
        local entpos = Vector3(inst.Transform:GetWorldPosition() )
        local ents = TheSim:FindEntities(entpos.x,entpos.y,entpos.z, mathrange)
        
        for k,v in pairs(ents) do
        
        -------------------------------------------------------------------------------------------
        -- growth spell
            if v.components.crop then
                v.components.crop:DoGrow(TUNING.THISISLUCY_CROP_TIME)
            end

            if v.components.growable and v.components.pickable and not v.components.crop then
                v.components.growable:DoGrowth()
                v.components.pickable:FinishGrowing()
            end
            --if v:HasTag("marsh_bush") or v:HasTag("berrybush") or v:HasTag("berrybush2") or v:HasTag("sapling") or v:HasTag("grass") and v.components.growable and not v:HasTag("stump") and not v:HasTag("tree") then
            --    v.components.growable:DoGrowth()
            --end

            if v:HasTag("tree") and v.components.growable and not v:HasTag("stump") then
                v.components.growable:DoGrowth()
            end
            
            if v:HasTag("grass") or v:HasTag("bush") and v.components.pickable then
            -- check for custom tag
                --print("   has tag 'grass' and is 'pickable'   ")
            end
            
            
            if v.components.pickable then        --or v.components.growable then
                v.components.pickable:FinishGrowing()
                v.components.pickable.numtoharvest = 2
            end
        -------------------------------------------------------------------------------------------
        -- spawn spell
        --[[
            if v.components.childspawner and v:HasTag("hive") and not v:HasTag("spiderden") then
                v.components.childspawner:SetMaxChildren(3)
                v.components.childspawner:SetRegenPeriod(0)
                v.components.childspawner:SetSpawnPeriod(0)
                v.components.childspawner:ReleaseAllChildren()
                --v.components.combat:SetTarget(v)
                --v.components.childspawner:StartRegen()
                --v.components.childspawner:StartSpawning()
                
            elseif v.components.childspawner and v:HasTag("spiderden") then
                v.components.childspawner:SetMaxChildren(3)
                v.components.childspawner:SetRegenPeriod(0)
                v.components.childspawner:SetSpawnPeriod(0)
                v.components.childspawner:ReleaseAllChildren()
                --v.components.combat:SetTarget(v)
                --v.components.childspawner:StartRegen()
                --v.components.childspawner:StartSpawning()
                
            elseif v.components.childspawner and not v:HasTag("spiderden") and not v:HasTag("hive") then
                v.components.childspawner:SetMaxChildren(3)
                v.components.childspawner:SetRegenPeriod(0)
                v.components.childspawner:SetSpawnPeriod(0)
                v.components.childspawner:ReleaseAllChildren()
                --v.components.combat:SetTarget(v)
                --v.components.childspawner:StartRegen()
                --v.components.childspawner:StartSpawning()
            end
        ]]--
        end
    end)
end

local function pulse_light(inst)
    local s = GetSineVal(0.05, true, inst)
    local rad = Lerp(4, 5, s)
    local intentsity = Lerp(0.8, 0.7, s)
    local falloff = Lerp(0.8, 0.7, s)
    inst.Light:SetFalloff(falloff)
    inst.Light:SetIntensity(intentsity)
    inst.Light:SetRadius(rad)
    inst.colour_list = math.random(#lightfade_colours)
    inst.Light:SetColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3])
    inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
end
local function colourfade_light(inst)
    inst.colour_list = math.random(#lightfade_colours)
    inst.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
    inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
end
local function auratest(inst, target)
    return target:HasTag("player") or target:HasTag("leader")
end
local function sparkslight(inst, dt)
    inst.colour_list = math.random(#lightfade_colours)
    if GetClock():IsDay() then
        inst.sparks = inst.sparks - dt
        if inst.sparks <= 0 then
            inst.sparks = 3+math.random()*1
            local pos = Vector3(inst.Transform:GetWorldPosition())
            local spark = SpawnPrefab("sparks")
            spark.Transform:SetPosition(pos:Get())
            spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
        end
    elseif GetClock():IsDusk() then
        inst.sparks = inst.sparks - dt
        if inst.sparks <= 0 then
            GetClock():DoLightningLighting(.1)
            inst.sparks = 3+math.random()*3
            local pos = Vector3(inst.Transform:GetWorldPosition())
            local spark = SpawnPrefab("sparks")
            spark.Transform:SetPosition(pos:Get())
            spark.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
            spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
            GetPlayer().components.playercontroller:ShakeCamera(inst, "SIDE", TUNING.DUSK_SEGS_DEFAULT, 0.01, 0.1, 0.1)
        end
    elseif GetClock():IsNight() then
        inst.sparks = inst.sparks - dt
        if inst.sparks <= 0 then
            GetClock():DoLightningLighting(.1)
            inst.sparks = 1+math.random()*9
            local pos = Vector3(inst.Transform:GetWorldPosition())
            local spark = SpawnPrefab("sparks")
            spark.Transform:SetPosition(pos:Get())
            spark.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
            spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
            GetPlayer().components.playercontroller:ShakeCamera(inst, "SIDE", TUNING.NIGHT_SEGS_DEFAULT, 0.01, 0.1, 0.1)
        end
    end
end

local function fn(sim)

    local function OnEquip(inst, owner)
        --owner.AnimState:OverrideSymbol
        owner.AnimState:OverrideSymbol("swap_object", "swap_lucy_axe", "swap_lucy_axe")
        owner.AnimState:Show("ARM_carry")
        owner.AnimState:Hide("ARM_normal")
        
        --Enable 1 Time Lightning Effect to Show Equipped
        local light = inst.entity:AddLight()        
        light:Enable(true)

        --FX lightning Intervals
        GetClock():DoLightningLighting(SEGTIME_SHORT)
        GetClock():DoLightningLighting(SEGTIME_HALF)
        GetClock():DoLightningLighting(SEGTIME)
        GetClock():DoLightningLighting(1)

        --Bloom Animations Handler
        inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )

        --Properties Update Fn on Time
        inst.dodelta_tasks     = inst:DoPeriodicTask(SEGTIME, dodelta_tasks)
        inst.updatedamage     = inst:DoPeriodicTask(SEGTIME_HALF, updatedamage)
        inst.chopupdate     = inst:DoPeriodicTask(SEGTIME, chopupdate)

        owner.components.locomotor:SetSlowMultiplier( TUNING.THISISLUCY_DECREASE_WALKCREEPSPEED )
        owner.components.locomotor.pathcaps     = {triggerscreep = true}
        owner.components.locomotor.fasteronroad = false
        owner.components.locomotor.isrunning     = false
        owner.components.locomotor.slowmultiplier = TUNING.THISISLUCY_DECREASE_WALKSLOWMULT
        owner.components.locomotor.fastmultiplier = TUNING.THISISLUCY_DECREASE_WALKFASTMULT
        owner.components.locomotor.groundspeedmultiplier = TUNING.THISISLUCY_DECREASE_WALKGROUNDMULT
        owner.components.locomotor.walkspeed = TUNING.THISISLUCY_DECREASE_WALKSPEED
        owner.components.locomotor.runspeed  = TUNING.THISISLUCY_DECREASE_RUNSPEED

        --Disbled Features > 1.73
        --#####################################################
        --owner.SoundEmitter:PlaySound("dontstarve/creatures/leif/livinglog_burn")
        --owner.SoundEmitter:SetParameter("livinglog_burn", "intensity", 0.01)
        --#####################################################

    end

    local function OnUnequip(inst, owner)
        owner.AnimState:Hide("ARM_carry")
        owner.AnimState:Show("ARM_normal")

        --Enable 1 Time Lightning Effect to Show Unequipped
        local light = inst.entity:AddLight()        
        light:Enable(true)

        if inst.dodelta_tasks then
            inst.dodelta_tasks:Cancel()
            inst.dodelta_tasks = nil
            inst.SoundEmitter:KillSound("livinglog_burn_1")
            inst.SoundEmitter:KillSound("livinglog_burn_2")
            inst.SoundEmitter:KillSound("livinglog_burn_3")
            inst.SoundEmitter:KillSound("livinglog_burn_4")
            inst.SoundEmitter:KillSound("livinglog_burn")
            ------
            inst.SoundEmitter:KillSound("thunder_far_1")
            inst.SoundEmitter:KillSound("thunder_far_2")
            inst.SoundEmitter:KillSound("thunder_far_3")
            inst.SoundEmitter:KillSound("thunder_far_4")
            inst.SoundEmitter:KillSound("thunder_close")
        end
    
        if inst.updatedamage then
            inst.updatedamage:Cancel()
            inst.updatedamage = nil
        end
        
        if inst.chopupdate then
            inst.chopupdate:Cancel()
            inst.chopupdate = nil
        end

        if inst.growfntask then
            inst.growfntask:Cancel()
            inst.growfntask = nil
        end
        
        owner.AnimState:SetBloomEffectHandle( "" )
        owner.SoundEmitter:PlaySound("dontstarve/wilson/onemanband", "onemanband")
        owner.SoundEmitter:SetParameter("onemanband", "intensity", 0.01)
        owner.components.locomotor.pathcaps = {triggerscreep = false}
        owner.components.locomotor.fasteronroad = true
        owner.components.locomotor.slowmultiplier = 0.6
        owner.components.locomotor.fastmultiplier = 1.3
        owner.components.locomotor.groundspeedmultiplier = 1.0
        owner.components.locomotor.walkspeed = TUNING.WILSON_WALK_SPEED -- 4
        owner.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED -- 6    
        owner.components.hunger:Resume()
        owner.components.sanity.ignore = false
        owner.components.health.redirect = nil
        
        GetSeasonManager():DefaultLightningDelays()
        GetSeasonManager():StartPrecip()
    end
    
        local inst = CreateEntity()
        if (inst) then
            inst.components.Recipe.thisislucy:Cancel()
            inst.components.Recipe.thisislucy = nil
        end
        local trans = inst.entity:AddTransform()
        local anim = inst.entity:AddAnimState()
        inst.entity:AddSoundEmitter()

        MakeInventoryPhysics(inst)
        
        anim:SetBank("Lucy_axe")
        anim:SetBuild("Lucy_axe")
        anim:PlayAnimation("idle")

        inst:AddTag("irreplaceable")
        local minimap = inst.entity:AddMiniMapEntity()
        minimap:SetIcon("lucy_axe.png")


        --Special Lighting FX
        local light = inst.entity:AddLight()
        light:SetFalloff(0.3)
        light:SetIntensity(.9)
        light:SetRadius(2)
        light:SetColour(235/255,121/255,12/255)
        light:Enable(true)

        -- inst:AddTag("fx") Commented out due to tunning; If you have 'fx' why add it 2 times?
        inst:AddTag("firefx")
        inst:AddTag("sharp")

        ---------------------------------------------

        inst.pulselight = inst:DoPeriodicTask(0, pulse_light)
        inst.colourfade = inst:DoPeriodicTask(30, colourfade_light)
        inst.sparks = 1
        inst.sparkslight = inst:DoPeriodicTask(SEGTIME_SHORT, function() sparkslight(inst, SEGTIME) end)

        inst.colour_list = math.random(#lightfade_colours)
        inst.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],.5)
        inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" ) --shaders/anim.ksh
        
        GetClock():DoLightningLighting(.1)
        GetSeasonManager():DoMediumLightning()
        inst.SoundEmitter:SetParameter("miniearthquake", "intensity", 0.01)

        ---------------------------------------------
        --Properties /Parameters

        inst:AddComponent("tool")
        inst.components.tool:SetAction(ACTIONS.CHOP, 3)
        inst.components.tool:SetAction(ACTIONS.MINE, 3) --Added mining effect due to increased Aura Values
        inst.components.tool:SetAction(ACTIONS.HAMMER)

        inst:AddComponent("weapon")
        inst.components.weapon:SetDamage(TUNING.SPEAR_DAMAGE*1.625)

        inst:AddComponent("inspectable")

        inst:AddComponent("propagator")
        inst.components.propagator.heatoutput = math.random(10,45)
        inst.components.propagator.spreading = false
        inst.components.propagator:StartUpdating()

        inst:AddComponent("heater")
        inst.components.heater.heat = 5 + math.random(10)

        inst:AddComponent("sanityaura")
        inst.components.sanityaura.aura = -0.15

        inst:AddComponent("aura")
        inst.components.aura.radius = 1
        inst.components.aura.tickperiod = .01
        inst.components.aura.ignoreallies = true
        inst.components.aura.auratestfn = auratest

        inst:AddComponent("named")
        inst.components.named:SetName("This Is Lucy..and sometimes a horrirble...")
        inst.components.named.possiblenames = STRINGS.THISISLUCY_NAMES
        inst.components.named:PickNewName()        

        inst:AddComponent("inventoryitem")
        inst.components.inventoryitem.imagename = "thisislucy"
        inst.components.inventoryitem.atlasname = "images/inventoryimages/thisislucy.xml"
        inst.components.inventoryitem:GetImage()
        inst.components.inventoryitem:GetAtlas()
            
        inst:AddComponent( "spawner" )
        inst.components.spawner:Configure( "crow", SEGTIME_HALF)
        inst.components.spawner:ReleaseChild()
        inst.components.spawner.nextspawntime = 1
        inst.components.spawner:SetOnlySpawnOffscreen(false)

        inst:AddComponent("equippable")
        inst.components.equippable:SetOnEquip( OnEquip )
        inst.components.equippable:SetOnUnequip( OnUnequip )

        return inst


end



return  Prefab("common/inventory/thisislucy", fn, assets, prefabs)

Link to comment
Share on other sites

1st) put spoilertags around each file, so the content can be minimized, i have no idea where your prefab starts


--way to much code :razz:


2nd) iam not sure if i understood what u want, as far as i understand the mod, it adds lucy to all characters' startinventories but woodie's:
local function lucyloader(inst)    local st_inv = inst.components.inventory.starting_inventory    if (st_inv) then        table.insert(st_inv, "thisislucy")            else        inst.components.inventory.starting_inventory = {"thisislucy"}        Global.Recipe.thisislucy:Cancel()            end    endfor k,prefab in ipairs(GLOBAL.MODCHARACTERLIST) do        AddPrefabPostInit(prefab, lucyloader)endfor k,prefab in ipairs(CHARACTERLIST) do    if prefab ~= "woodie" then        AddPrefabPostInit(prefab, lucyloader)    endend



And u say u want all character to have lucy only once. Why do u even need the recipe now?
Link to comment
Share on other sites

yes this is correct! but the problem comes in when a person is given a Custom name string that requires a input at startup (ei. hero in the dark mod) none of that mods charactors start with the lucy item unless the for statement is disabled... and seeing as though i dont know where the specific prefabs code is located in that mod, i decided to go with the lesser of 2 evils, so to speak.

Link to comment
Share on other sites

also sorry about the mess prior.... lol i dont post on forums much so im lacking in the proper forum etiquette... :/

 



local assets =
{
Asset("ANIM", "anim/lucy_axe.zip"),
Asset("ANIM", "anim/swap_lucy_axe.zip"),
Asset("ATLAS", "images/inventoryimages/thisislucy.xml"),
}
prefabs = {
"explode_small",
"sparks",
}

local lightfade_colours =
{
{128/255,255/255,255/255},
{254/255,217/255,129/255},
{192/255,192/255,192/255},
{240/255,240/255,240/255},
{157/255,213/255,43/255},
{180/255,180/255,231/255},
}

local player = GetPlayer()
local owner = GetPlayer()

-- dodelta_tasks
local SEGTIME = TUNING.SEG_TIME --30
local SEGTIME_HALF = 15
local SEGTIME_SHORT = 7.5

-- delta, time values - dodelta_tasks
local DODELTA_RAND = -math.random(1, 5)
local HEALTH_DODELTA = -1
local HUNGER_DODELTA = -5
local SANITY_DODELTA = -10

local TIME = -3
local SANITY_TIME = -121
--local TIMETOABSORB = math.random(1, 10)
--local up_timer = 121
--local down_timer = -121

local ON = true
local OFF = false

-- health, hunger, sanity
local function dodelta_tasks(player)
local player = GetPlayer()
if player.components.hunger then
player.SoundEmitter:PlaySound("dontstarve/rain/thunder_close", "thunder_far_2")
player.SoundEmitter:SetParameter("thunder_far_2", "intensity", 0.01)
player.components.hunger:DoDelta(HUNGER_DODELTA, TIME)
end

if player.components.sanity then
player.components.sanity:DoDelta(SANITY_DODELTA, SANITY_TIME)
end

if player.components.health and not player.components.health:IsDead() then
player.components.health.invincible = OFF
player.components.health:DoDelta(HEALTH_DODELTA, TIME, nil, true)
end
end

local function chopupdate(inst)
if inst.components.tool and inst:HasTag("thisislucy") then
GetClock():DoLightningLighting(1)
inst.components.tool:SetAction(ACTIONS.CHOP, math.random(3, 9) )
end
end

local function updatedamage(inst, owner, weapon)
local owner = GetPlayer()
local weapon = inst.components.weapon

--if inst.growfntask then
-- inst.growfntask:Cancel()
-- inst.growfntask = nil
--end

if weapon and inst.components.inventoryitem then
GetClock():DoLightningLighting(1)

--#####################################################
-- disabled >> 1.73
--owner.SoundEmitter:PlaySound("dontstarve/creatures/leif/livinglog_burn", "livinglog_burn")
--owner.SoundEmitter:SetParameter("livinglog_burn", "intensity", 0.01)
--#####################################################

inst.components.weapon:SetDamage(math.random()*12)
end
---------------------------------------------
inst.growfntask = inst:DoTaskInTime(121, function()
GetClock():DoLightningLighting(121)
GetSeasonManager():LightningWhenRaining()

local mathrange = math.random(5, 15)
local entpos = Vector3(inst.Transform:GetWorldPosition() )
local ents = TheSim:FindEntities(entpos.x,entpos.y,entpos.z, mathrange)

for k,v in pairs(ents) do

-------------------------------------------------------------------------------------------
-- growth spell
if v.components.crop then
v.components.crop:DoGrow(TUNING.THISISLUCY_CROP_TIME)
end

if v.components.growable and v.components.pickable and not v.components.crop then
v.components.growable:DoGrowth()
v.components.pickable:FinishGrowing()
end
--if v:HasTag("marsh_bush") or v:HasTag("berrybush") or v:HasTag("berrybush2") or v:HasTag("sapling") or v:HasTag("grass") and v.components.growable and not v:HasTag("stump") and not v:HasTag("tree") then
-- v.components.growable:DoGrowth()
--end

if v:HasTag("tree") and v.components.growable and not v:HasTag("stump") then
v.components.growable:DoGrowth()
end

if v:HasTag("grass") or v:HasTag("bush") and v.components.pickable then
-- check for custom tag
--print(" has tag 'grass' and is 'pickable' ")
end


if v.components.pickable then --or v.components.growable then
v.components.pickable:FinishGrowing()
v.components.pickable.numtoharvest = 2
end
-------------------------------------------------------------------------------------------
-- spawn spell
--[[
if v.components.childspawner and v:HasTag("hive") and not v:HasTag("spiderden") then
v.components.childspawner:SetMaxChildren(3)
v.components.childspawner:SetRegenPeriod(0)
v.components.childspawner:SetSpawnPeriod(0)
v.components.childspawner:ReleaseAllChildren()
--v.components.combat:SetTarget(v)
--v.components.childspawner:StartRegen()
--v.components.childspawner:StartSpawning()

elseif v.components.childspawner and v:HasTag("spiderden") then
v.components.childspawner:SetMaxChildren(3)
v.components.childspawner:SetRegenPeriod(0)
v.components.childspawner:SetSpawnPeriod(0)
v.components.childspawner:ReleaseAllChildren()
--v.components.combat:SetTarget(v)
--v.components.childspawner:StartRegen()
--v.components.childspawner:StartSpawning()

elseif v.components.childspawner and not v:HasTag("spiderden") and not v:HasTag("hive") then
v.components.childspawner:SetMaxChildren(3)
v.components.childspawner:SetRegenPeriod(0)
v.components.childspawner:SetSpawnPeriod(0)
v.components.childspawner:ReleaseAllChildren()
--v.components.combat:SetTarget(v)
--v.components.childspawner:StartRegen()
--v.components.childspawner:StartSpawning()
end
]]--
end
end)
end

local function pulse_light(inst)
local s = GetSineVal(0.05, true, inst)
local rad = Lerp(4, 5, s)
local intentsity = Lerp(0.8, 0.7, s)
local falloff = Lerp(0.8, 0.7, s)
inst.Light:SetFalloff(falloff)
inst.Light:SetIntensity(intentsity)
inst.Light:SetRadius(rad)
inst.colour_list = math.random(#lightfade_colours)
inst.Light:SetColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3])
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
end
local function colourfade_light(inst)
inst.colour_list = math.random(#lightfade_colours)
inst.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
end
local function auratest(inst, target)
return target:HasTag("player") or target:HasTag("leader")
end
local function sparkslight(inst, dt)
inst.colour_list = math.random(#lightfade_colours)
if GetClock():IsDay() then
inst.sparks = inst.sparks - dt
if inst.sparks <= 0 then
inst.sparks = 3+math.random()*1
local pos = Vector3(inst.Transform:GetWorldPosition())
local spark = SpawnPrefab("sparks")
spark.Transform:SetPosition(pos:Get())
spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
end
elseif GetClock():IsDusk() then
inst.sparks = inst.sparks - dt
if inst.sparks <= 0 then
GetClock():DoLightningLighting(.1)
inst.sparks = 3+math.random()*3
local pos = Vector3(inst.Transform:GetWorldPosition())
local spark = SpawnPrefab("sparks")
spark.Transform:SetPosition(pos:Get())
spark.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
GetPlayer().components.playercontroller:ShakeCamera(inst, "SIDE", TUNING.DUSK_SEGS_DEFAULT, 0.01, 0.1, 0.1)
end
elseif GetClock():IsNight() then
inst.sparks = inst.sparks - dt
if inst.sparks <= 0 then
GetClock():DoLightningLighting(.1)
inst.sparks = 1+math.random()*9
local pos = Vector3(inst.Transform:GetWorldPosition())
local spark = SpawnPrefab("sparks")
spark.Transform:SetPosition(pos:Get())
spark.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],1)
spark.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
GetPlayer().components.playercontroller:ShakeCamera(inst, "SIDE", TUNING.NIGHT_SEGS_DEFAULT, 0.01, 0.1, 0.1)
end
end
end

local function fn(sim)

local function OnEquip(inst, owner)
--owner.AnimState:OverrideSymbol
owner.AnimState:OverrideSymbol("swap_object", "swap_lucy_axe", "swap_lucy_axe")
owner.AnimState:Show("ARM_carry")
owner.AnimState:Hide("ARM_normal")

--Enable 1 Time Lightning Effect to Show Equipped
local light = inst.entity:AddLight()
light:Enable(true)

--FX lightning Intervals
GetClock():DoLightningLighting(SEGTIME_SHORT)
GetClock():DoLightningLighting(SEGTIME_HALF)
GetClock():DoLightningLighting(SEGTIME)
GetClock():DoLightningLighting(1)

--Bloom Animations Handler
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )

--Properties Update Fn on Time
inst.dodelta_tasks = inst:DoPeriodicTask(SEGTIME, dodelta_tasks)
inst.updatedamage = inst:DoPeriodicTask(SEGTIME_HALF, updatedamage)
inst.chopupdate = inst:DoPeriodicTask(SEGTIME, chopupdate)

owner.components.locomotor:SetSlowMultiplier( TUNING.THISISLUCY_DECREASE_WALKCREEPSPEED )
owner.components.locomotor.pathcaps = {triggerscreep = true}
owner.components.locomotor.fasteronroad = false
owner.components.locomotor.isrunning = false
owner.components.locomotor.slowmultiplier = TUNING.THISISLUCY_DECREASE_WALKSLOWMULT
owner.components.locomotor.fastmultiplier = TUNING.THISISLUCY_DECREASE_WALKFASTMULT
owner.components.locomotor.groundspeedmultiplier = TUNING.THISISLUCY_DECREASE_WALKGROUNDMULT
owner.components.locomotor.walkspeed = TUNING.THISISLUCY_DECREASE_WALKSPEED
owner.components.locomotor.runspeed = TUNING.THISISLUCY_DECREASE_RUNSPEED

--Disbled Features > 1.73
--#####################################################
--owner.SoundEmitter:PlaySound("dontstarve/creatures/leif/livinglog_burn")
--owner.SoundEmitter:SetParameter("livinglog_burn", "intensity", 0.01)
--#####################################################

end

local function OnUnequip(inst, owner)
owner.AnimState:Hide("ARM_carry")
owner.AnimState:Show("ARM_normal")

--Enable 1 Time Lightning Effect to Show Unequipped
local light = inst.entity:AddLight()
light:Enable(true)

if inst.dodelta_tasks then
inst.dodelta_tasks:Cancel()
inst.dodelta_tasks = nil
inst.SoundEmitter:KillSound("livinglog_burn_1")
inst.SoundEmitter:KillSound("livinglog_burn_2")
inst.SoundEmitter:KillSound("livinglog_burn_3")
inst.SoundEmitter:KillSound("livinglog_burn_4")
inst.SoundEmitter:KillSound("livinglog_burn")
------
inst.SoundEmitter:KillSound("thunder_far_1")
inst.SoundEmitter:KillSound("thunder_far_2")
inst.SoundEmitter:KillSound("thunder_far_3")
inst.SoundEmitter:KillSound("thunder_far_4")
inst.SoundEmitter:KillSound("thunder_close")
end

if inst.updatedamage then
inst.updatedamage:Cancel()
inst.updatedamage = nil
end

if inst.chopupdate then
inst.chopupdate:Cancel()
inst.chopupdate = nil
end

if inst.growfntask then
inst.growfntask:Cancel()
inst.growfntask = nil
end

owner.AnimState:SetBloomEffectHandle( "" )
owner.SoundEmitter:PlaySound("dontstarve/wilson/onemanband", "onemanband")
owner.SoundEmitter:SetParameter("onemanband", "intensity", 0.01)
owner.components.locomotor.pathcaps = {triggerscreep = false}
owner.components.locomotor.fasteronroad = true
owner.components.locomotor.slowmultiplier = 0.6
owner.components.locomotor.fastmultiplier = 1.3
owner.components.locomotor.groundspeedmultiplier = 1.0
owner.components.locomotor.walkspeed = TUNING.WILSON_WALK_SPEED -- 4
owner.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED -- 6
owner.components.hunger:Resume()
owner.components.sanity.ignore = false
owner.components.health.redirect = nil

GetSeasonManager():DefaultLightningDelays()
GetSeasonManager():StartPrecip()
end

local inst = CreateEntity()
if (inst) then
inst.components.Recipe.thisislucy:Cancel()
inst.components.Recipe.thisislucy = nil
end
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()

MakeInventoryPhysics(inst)

anim:SetBank("Lucy_axe")
anim:SetBuild("Lucy_axe")
anim:PlayAnimation("idle")

inst:AddTag("irreplaceable")
local minimap = inst.entity:AddMiniMapEntity()
minimap:SetIcon("lucy_axe.png")


--Special Lighting FX
local light = inst.entity:AddLight()
light:SetFalloff(0.3)
light:SetIntensity(.9)
light:SetRadius(2)
light:SetColour(235/255,121/255,12/255)
light:Enable(true)

-- inst:AddTag("fx") Commented out due to tunning; If you have 'fx' why add it 2 times?
inst:AddTag("firefx")
inst:AddTag("sharp")

---------------------------------------------

inst.pulselight = inst:DoPeriodicTask(0, pulse_light)
inst.colourfade = inst:DoPeriodicTask(30, colourfade_light)
inst.sparks = 1
inst.sparkslight = inst:DoPeriodicTask(SEGTIME_SHORT, function() sparkslight(inst, SEGTIME) end)

inst.colour_list = math.random(#lightfade_colours)
inst.AnimState:SetMultColour(lightfade_colours[inst.colour_list][1],lightfade_colours[inst.colour_list][2],lightfade_colours[inst.colour_list][3],.5)
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" ) --shaders/anim.ksh

GetClock():DoLightningLighting(.1)
GetSeasonManager():DoMediumLightning()
inst.SoundEmitter:SetParameter("miniearthquake", "intensity", 0.01)

---------------------------------------------
--Properties /Parameters

inst:AddComponent("tool")
inst.components.tool:SetAction(ACTIONS.CHOP, 3)
inst.components.tool:SetAction(ACTIONS.MINE, 3) --Added mining effect due to increased Aura Values
inst.components.tool:SetAction(ACTIONS.HAMMER)

inst:AddComponent("weapon")
inst.components.weapon:SetDamage(TUNING.SPEAR_DAMAGE*1.625)

inst:AddComponent("inspectable")

inst:AddComponent("propagator")
inst.components.propagator.heatoutput = math.random(10,45)
inst.components.propagator.spreading = false
inst.components.propagator:StartUpdating()

inst:AddComponent("heater")
inst.components.heater.heat = 5 + math.random(10)

inst:AddComponent("sanityaura")
inst.components.sanityaura.aura = -0.15

inst:AddComponent("aura")
inst.components.aura.radius = 1
inst.components.aura.tickperiod = .01
inst.components.aura.ignoreallies = true
inst.components.aura.auratestfn = auratest

inst:AddComponent("named")
inst.components.named:SetName("This Is Lucy..and sometimes a horrirble...")
inst.components.named.possiblenames = STRINGS.THISISLUCY_NAMES
inst.components.named:PickNewName()

inst:AddComponent("inventoryitem")
inst.components.inventoryitem.imagename = "thisislucy"
inst.components.inventoryitem.atlasname = "images/inventoryimages/thisislucy.xml"
inst.components.inventoryitem:GetImage()
inst.components.inventoryitem:GetAtlas()

inst:AddComponent( "spawner" )
inst.components.spawner:Configure( "crow", SEGTIME_HALF)
inst.components.spawner:ReleaseChild()
inst.components.spawner.nextspawntime = 1
inst.components.spawner:SetOnlySpawnOffscreen(false)

inst:AddComponent("equippable")
inst.components.equippable:SetOnEquip( OnEquip )
inst.components.equippable:SetOnUnequip( OnUnequip )

return inst
end

return Prefab("common/inventory/thisislucy", fn, assets, prefabs)

 

-- locals -----------------------------------
local STRINGS = GLOBAL.STRINGS
local TUNING = GLOBAL.TUNING
local package = GLOBAL.package
---------------------------------------------

Assets =
{
Asset("IMAGE", "icon.tex"),
Asset("ATLAS", "icon.xml"),
}
package.path = "mods\\This Is Lucy 1.73.5 -giants-\\scripts\\?.lua;"..package.path
-- version 1.73
versnr = "1.73.5"
STRINGS.THISISLUCY_VERSION = versnr
update = "'Reign of Giants'"
placeholder = "\n******************************************************\n******************************************************\n"
print("\n",placeholder,"\n","\t","This Is Lucy","\n","\t","Version: ",versnr,"\n","\t","Update: ",update,"\n\n","\t","DontStarver (2014)","\n",placeholder)
---------------------------------------------
-- strings
GLOBAL.STRINGS.THISISLUCY_NAMES = {"This Is Lucy", ".....", "..a horrirble..axe", "????", " "}
GLOBAL.STRINGS.NAMES.THISISLUCY = "This Is Lucy"
GLOBAL.STRINGS.RECIPE_DESC.THISISLUCY = "Axe with a \nmysterious magical effect..."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.THISISLUCY = "Axe with a \nmysterious magical effect..."
-- TUNINGS
TUNING.THISISLUCY_DAMAGE = 10
TUNING.THISISLUCY_DECREASE_WALKSPEED = 4
TUNING.THISISLUCY_DECREASE_RUNSPEED = 6
TUNING.THISISLUCY_DECREASE_WALKCREEPSPEED = 0.85
TUNING.THISISLUCY_DECREASE_WALKSPEEDMULT = 0.8
TUNING.THISISLUCY_DECREASE_WALKFASTMULT = 1.3
TUNING.THISISLUCY_DECREASE_WALKSLOWMULT = 0.6
TUNING.THISISLUCY_DECREASE_WALKGROUNDMULT = 1.0
TUNING.THISISLUCY_CROP_TIME = 5
---------------------------------------------
PrefabFiles = {"thisislucy"}
---------------------------------------------

local thisislucy = GLOBAL.Recipe("thisislucy", {GLOBAL.Ingredient("darkpetals", 20), GLOBAL.Ingredient("nightmarefuel", 5), GLOBAL.Ingredient("livinglog", 5), GLOBAL.Ingredient("boards", 15)}, GLOBAL.RECIPETABS.TOOLS, GLOBAL.TECH.NONE, placeholder)
-- local thisislucy = GLOBAL.Recipe("thisislucy", {GLOBAL.Ingredient("petals", 1)}, GLOBAL.RECIPETABS.TOOLS, GLOBAL.TECH.NONE)
thisislucy.atlas = "images/inventoryimages/thisislucy.xml"

local function lucyloader(inst)
local st_inv = inst.components.inventory.starting_inventory
if (st_inv) then
table.insert(st_inv, "thisislucy")
else
inst.components.inventory.starting_inventory = {"thisislucy"}
Global.Recipe.thisislucy:Cancel()

end
end
for k,prefab in ipairs(GLOBAL.MODCHARACTERLIST) do
AddPrefabPostInit(prefab, lucyloader)
end
for k,prefab in ipairs(CHARACTERLIST) do
if prefab ~= "woodie" then
AddPrefabPostInit(prefab, lucyloader)
end
end
Link to comment
Share on other sites

well the quick and dirty approach would be adding

AddSimPostInit(function() GetPlayer().components.inventory:GiveItem(SpawnPrefab('thisislucy')) end )

to the modmain of thisislucy(dont nail me on the synthax here). AddSimPostInit runs after the game has been initialized. This however doesnt work in dont starve together anymore, and i bet there's a better way to do this, that even works in DST. Do u need it for DST?

Link to comment
Share on other sites

no I do not this is fine, I dont own DST atm.... thank you. I will definitely give it a shot! thank you again. ps. i have been looking for a page that has a list of the syntax constructors, classes, packages and components to refer to in order to create mods for DS but no avail. i dont understand how and where people have found these reserved terms in order to create their mods!!! I mean, is this specific to the .lua programming language itself or DS?

Link to comment
Share on other sites

well, the synthax itself is lua, but mostly u need to know how dont starve is constructed. just look through the game files or other mods for similar thing to what u want to do and use the searchfunction on the forum here. for me, the most useful mods to learn stuff from, have been "link the hero", "satori" and the "creature mod tutorial"-mods. but most stuff i just find in the gamefiles.

 

for example, one thing i recently learned, is that actions get stored in a actiontable, thats why u can just access actions via GLOBAL.ACTIONS and override its functions or strings in the modmain. components on the otherhand dont get put into a table, and u have to localy reference it in the prefab that uses it, to localy override its functions. and thats just a thing how dont starve is constructed, thats not necessary due to lua.

 

and yes, evertime i make a bigger change to the game, it keeps crashing for hours and i have to look into the logfile everytime and try to understand the problem and try something else to fix it.

 

"n tools"-mod is also pretty usefull and using the print() function to find problems.

 

also, in https://docs.google.com/spreadsheets/d/1oLEjOOJ9-k9PC_JQMw7y5vCNqGDU1niw_XnJCxkBxSU/ u can find all the functions that come from the executable, everything else has to come from somewhere in the luafiles, so that was also pretty useful for me.

also, u have 5 posts now, u should be able to modify your posts, pls put spoilertags in your top post, scrolling down here everytime is becoming a pain^^

Link to comment
Share on other sites

@Seiai,

 

I should have mentioned when I linked you previously-- since that list is for DST functions and may differ from DS, there are ways that you can list DS's UserData(C++) functions via lua.  With any UserData object, when you want to expose functions to the Lua interface, you have to store references to them on the object's metatable.  That means with any UserData object, you can display all available C++ API functions like so:

--using entity as an example, any UserData object works (transform, etc.)print(table.inspect(getmetatable(inst.entity)))

I like to store that somewhere useful, eg

-- there is very rarely anything I do to the output of table.inspect other than print it, -- so might as well include it.table.ins = function(obj)     print(table.inspect(getmetatable(obj)))end

FWIW Components are loaded through require in entityscript.lua, which means that technically they do get cached, but since it gets cached as a factory function, there's not a lot you can do about it.

 

But that doesn't matter all that much, because you can just use AddComponentPostInit() to tweak every component of a given type just after instantiation.

Link to comment
Share on other sites

@Talintid,

 

It's totally worth reading a few tutorials on Lua.  Lua is a super, super easy language to pick up compared to the vast majority of languages.  There are really only a few very small handfuls of features built in to Lua-- most is added on top of it.

 

Read through the game files as much as you can stomach.  Use a good file search program(the default windows one is god awful) to search through the Lua source for things you want to figure out. Pop open the log file in any program that will automatically update it when it's changed, and figure out why your game is crashing repeatedly when you tweak something(happens to everyone.)

Link to comment
Share on other sites

im on a mac lol i really dont know where the log file is stored at on here, do you? btw I code in C++, Java, Javascript and several other languages so to learn another shouldn't be that difficult, i hope... and thanks for the assistance guys and please believe that your help isnt unwarranted, i was planning on learning to learn to mod DS in order to update and create some well sought after and needed mods! Especially the ones that the creators have stalled on and no longer bother answering comments to the following community on. ^.^ But now i just need to learn how :wilson_cry:

Link to comment
Share on other sites

@Corrosive

 

Would you happen to know the syntax for 'checking' for an item in your inventory and performing an action if the item in found? ei checking for pickaxe and replacing it with spear. I want to know because i was to create a aura mod that turns flowers around player to evil evil flowers. lol I plan on making Zeraf from fairytale anime... :D

 

 

Link to comment
Share on other sites

your logfile should be in Home->Documents->Klei->DoNotStarveTogether.

Items:

Heavily depends on what exacty u want to do, just look in the inventory component, theres a lot of functions for a lot of things u might want to do.

for k,v in pairs(inst.components.Inventory:FindItems(function(item) --[[here u put the condition to return true for the right items, eg  return item.prefab=="prefabnameofyourauraitem"]] end)) do        --here goes the stuff u want to do, refereing to the item as v, eg v.components.auracaster:CastAura()    end
if u want to swap an item with another, u should use the Inventory:GetItemSlot(item) function and then item:Remove() the item in that slot and SpawnPrefab("newitem") in the new one with Inventory:GiveItem( inst, slot ).
Link to comment
Share on other sites

hmmmm.... i see that statement/ variable 'for k,v in pairs' alot in mods... so im guess that the common syntax for using the for statement in dont starve dont modding. Am i right? Cause i have noticed that there are no other variables declared for the exception of 'k,v'

Link to comment
Share on other sites

In Lua, there are two types of for loop-- numeric and generic. The numeric form is the standard style of for loop-- it works with a numeric variable:

for i=0, 10, 1 do    print(i)end

alternatively

local limit = 10local step = 2  --this increments i by 2 rather than 1 like the previous examplefor i = 0, limit, step do  --note you still need to initialize i directly in the for loop in this form    print(i)end

The other type of for loop, the generic for loop-- which is a bit more complicated-- uses functions called iterators.

Iterators often use specially designed functions called closuses to store iteration variables while the loop is running, but that's a topic for another time.

The generic for loop looks like this:

for result_var_1, result_var_2, ... result_var_n in iterator_function, invariant_state, initial_control_value do    --some stuff with the result_varsend

The most common use of this for loop is with one of the built in functions pairs or ipairs, which return the iterator function(which uses the built in function next), invariant state(the table being iterated over), and the initial control value(nil).

I'll hold off on further describing the mechanics of the generic for loop unless you really want an explanation ;)

If you're curious, you can manually do by hand the same thing that pairs or ipairs does using the console or a standalone lua interpreter in interactive mode:


(lines with ">" are entered into the console/interpreter, lines following those are output and commentary)

> fruits = { "banana", "strawberry", "kiwi" }> print( pairs(fruits) )function: 00421418 table: 0043A218 nil    <-- the iterator function(next),                                               the invariant state(the fruits table),                                              and the initial control variable(nil)> print( next(fruits, nil) )1 banana                        <-- 1 becomes the next control value, these would get                                    assigned to the result variables in a for loop                                    (which are typically k,v when using pairs/ipairs)> print( next(fruits, 1) )2 strawberry                    <-- 2 becomes the next control value> print( next(fruits, 2) )3 kiwi                          <-- 3 becomes the next control value> print( next(fruits, 3) )nil                             <-- control value is nil, so the for loop exits

 

 

As Blueberrys said, k and v are normally used because they are small but descriptive(I would argue that they aren't too descriptive, but since everyone is in agreement as to what they are, it works well enough due to pairs/ipairs being used so frequently.)
 
If you are iterating through a non-typical table though, such as one that uses functions or other tables as keys (instead of numbers or strings as is usual), you might opt to use a more descriptive variable names.
 
ex:

--[[ this would cache the return value of the 3 functions so you didn't have      to execute them every time.  You would really only do this for functions     that get run a LOT or were otherwise taxing on resources, in which case      you would manually update the cache only when necessary or able. ]]function f1() return 1 end  --\function f2() return 2 end  ----- pretend these are all much more complex ;)function f3() return 3 end  --/cache = {}-- Store the functions as keys, but don't cache them yet.-- false is used instead of nil because nil can't be stored in a tablecache[f1] = falsecache[f2] = falsecache[f3] = false-- Perhaps you only want to cache them when they're needed for the first time: function DoCachedFn(fn)    if not cache[fn] then        cache[fn] = fn()     end       return cache[fn]end-- Or perhaps you just want to cache them all at oncefunction CacheAll(cache)    for fn, last_result in pairs(cache) do   -- Here it would be useful to be more        if not last_result then              -- descriptive about what is being          cache[fn] = fn()                   -- retrieved from the table        end    end end

 

edit: minor clarification

Link to comment
Share on other sites

ah, i see says the blind man.... its amazing how differently for statements are used in lua vs other programming mediums i know... it seems like the for statement in lua is nothing more than a diluted version of a function. i need more documentation on this. ^_^

 

@Corrosive

im not against your further explaining 'for lua' statements as it may be undoubtedly helpful in things that i must know. Dont hold back. Im ready! :p

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

Please be aware that the content of this thread may be outdated and no longer applicable.

×
  • Create New...