Just add Lua

One of my requirements for the Altair project is to make it as moddable as possible. To that end, I decided that the base game itself should be implemented as a mod in order to ensure that modders would have as much support as I could possibly give them. My first step down that road was to embed a Lua interpreter and create abilities in Lua rather than hard coding them in C#. This effectively makes abilities data and the data is executable code which makes it incredibly powerful.

Below is my first draft of what an ability script written in Lua might look like. This script does technically run at the moment but ends up spitting out console messages when making the calls to the game object rather than actually doing anything useful.

Note I have never written anything in Lua before so if I’m doing something very wrong, please feel free to let me know in the comments.

--[[
init is called when the ability is first initialized and should setup the provided
ability object so that the UI knows how to make it available to the player

parameters:
	ability		the ability's setup object that should be modified
--]]
function init (ability)
	ability.Id = "base.selfdestruct"
	ability.Name = "Self Destruct"			-- name to display for this ability
	ability.Icon = "self_destruct.png"		-- the image to use as the icon for this ability
	ability.Description = "Destroy the selected ship and damage all surrounding ships."
											-- description to be displayed for this ability
	ability.Source = "PlayerShip"			-- ability can be activated only from the current player's selected ship
	ability.Target = "PlayerShip"			-- target the current player's selected ship for this ability
	ability.PowerCost = 100					-- cost in power to activate this ability
	ability.Cooldown = 0					-- the number of turns before this ability can be activated again
end

--[[
activate is called when the ability is activated and is where the ability's effect should occur

parameters:
	game		object used to sense and affect game state
	source		the object that triggered this ability
	targets		a table of the target objects for this ability
--]]
function activate (game, source, targets)
	range = 100		-- range of the explosion
	damage = 100000	-- damage to apply to any ships in range of the explosion

	-- since this is a single target ability, use targets[1] to select the first target from the table
	ships = game.GetShipsInRange(source.Position.Position, range)

	if ship ~= nil then
		for i = 1, #ships do
			game.ApplyDamage(ships[i], damage)
		end
	end

	game.ApplyDamage(source, damage)
end

At game start, Altair parses the abilities folder for Lua files and executes the init function in each script which is responsible for setting up the ability in the engine. The ability is a dead simple object that exposes the properties set in the init function along with a reference to the script object itself so that I can execute it later.

So how do we execute Lua code in Unity? I’m glad you asked! I stumbled across the MoonSharp project a while ago and decided to give it a shot for this implementation.

Calling in to the activate function in the Lua script looks like this:

public override void Execute() {
	var Abilities = AbilityLoader.GetAbilities();

	var ability = Abilities[AbilityId];
	var pGame = UserData.Create(GameField);
	var pSource = UserData.Create(new Ship {Id = "Ship1"});
	var ships = new List<Ship> {new Ship {Id = "Ship2"}, new Ship {Id = "Ship3"}};
	var pTargets = UserData.Create(ships);

	ability.Script.Call(ability.Script.Globals["activate"], pGame, pSource, pTargets);
}

This code is mostly just temporary while I’m testing out the integration but I’ll walk you through it anyway. The AbilityLoader is the code responsible for parsing the abilities and executing the init method but after that its this bad boy that calls the activate function in the script whenever the ability is activated.

As described in the comments of the Lua script, the parameters are; the GameField object which allows the script to sense and affect the game, the source ship that triggered this ability and finally the targets for this ability.

Just for the sake of completion, this is the LoadAbility method that’s doing the script initialization.

private Ability LoadAbility(string path) {
	var ability = new Ability();
	ability.Script = new Script();
	ability.Script.Options.DebugPrint = s => { Debug.Log(s); };
	UserData.RegisterType<Ability>();

	var scriptText = File.ReadAllText(path);
	ability.Script.DoString(scriptText);
	var pAbility = UserData.Create(ability);
	ability.Script.Call(ability.Script.Globals["init"], pAbility);

	return ability;
}

That guy there is calling the init function in the Lua script and passing it an Ability object that the Lua script populates and then I can store the whole thing for later.

That’s pretty much it. Integrating MoonSharp was pretty trivial.

This has of course brought a large portion of the rest of my codebase in to question as my game field isn’t actually smart enough to make this work properly yet, so I’m looking at paying down some technical debt in the not too distant future to get this all working the way I’m envisioning it should.

Overall I’m quite pleased with this approach although I am a little concerned that this is going to cause me grief with some platforms that demand AOT compilation, but one problem at a time right? :)

Leave a Reply