AI:Development:Lang:Lua

From Spring
Revision as of 09:49, 9 June 2009 by Hoijui (talk | contribs) ((really) create the page)
Jump to navigationJump to search

Writing a Lua AI

Introduction

Lua AIs are different

Lua for AIs is quite different from all the other AI languages supported by spring. Lua AIs use a compleetly different interface, and they can not be shipped separately, but only bundled with a mod.

Things to know

  • They have to be bundled with a mod. Therefore, you should consider contacting the mod developper(s) in question early, to see if they are at all interested in an AI.
  • A Lua AI is actually a regular gadget. The difference is just that it is listed in the mods LuaAI.lua file. See Lua Scripting for details.

How to start

For a start, choose a sinlge mod you want your AI to work with. You will also want to contact the mods developpwer(s) before you start to code, or soon thereafter.

Things you need to get comfortable with:

  • the Lua scripting language
  • Lua scripting for spring (gadgets)

You may combine learning Lua for spring with writing simplistic gadgets or widgets for spring, and publishing them in the forum, as this way you get practical training and feedback about your code from the pros, plus the community eventually gets a usefull addon. When you start feeling comfortable, you should inspect the code of Lua AIs that are already available. Source code of these AIs can be found in the mod archives, which you may open with 7zip, or it may be available separately (see #References.

Integrating the AI Gadget

This section explains everything you have to do to integrate your Lua AI into a mod. Whcih at the same time is everything that separates a Lua AI form a gadget.

In the root of the mods archive, you need the file LuaAI.lua, which should look about like this:

-- file: LuaAI.lua
local listOfLuaAIs = {
    {
        name="MyFirstAI",
        desc="Beats even the best players with Core, most others with Arm too",
    },
}
return listOfLuaAIs

besides all the other stuff you need for a gadget (you should know this by now), you will need something like this in your code:

function gadget:GetInfo()
    return {
        name = "MyFirstAI",
        desc = "An AI that knows how to play Mod X",
        author = "John Doe",
        date = "2020-12-31",
        license = "Public Domain",
        layer = 82,
        enabled = true
    }
end

function gadget:GameStart()

    -- Initialise AI for all teams that are set to use it
    for _,t in ipairs(Spring.GetTeamList()) do
        local _,_,_,ai,side = Spring.GetTeamInfo(t)
        if Spring.GetTeamLuaAI(t) == gadget:GetInfo().name then
            log(t, " assigned to "..gadget:GetInfo().name)
            local pos = {}
            local home_x,home_y,home_z = Spring.GetTeamStartPosition(t)
        end
    end
end

Thats it, the rest of the game is using regular gadget functions.

Enjoy!

References

C.R.A.I.G. is inside S44 and SWIW