MonoBoxedLua, sandboxed Lua for Mono/.NET

Heads up: This is a developer-oriented post

CraftStudio games are scripted in Lua, a nifty, lightweight scripting language. Since CraftStudio itself is written in C#, I needed a way to interface the C# CraftStudio engine with the game’s Lua scripts.

To do that, I forked MonoLuaInterface (which is itself a fork of LuaInterface) into MonoBoxedLua and made the following changes to make it into a more sandbox-like library:

  • MonoLuaInterface provided a two-way link between C# and Lua, allowing Lua to tap into any .NET libraries, so I removed that part.
  • I also disabled some Lua system libraries or functions which allowed direct access to the OS and disk input/output.

Today, prompted by a thread on the CraftStudio forums, I added a sample project to the repository showing how to expose functions and pass arguments (and properly dispose of them to avoid leaking memory).

Make your own Lua API from C#

The idea is very simple: create a new class which instantiate a Lua object and will contain all your API functions. Let’s call it MyLuaAPI:

using System;
using LuaInterface;

namespace LuaInterfaceSample
{
    class MyLuaAPI
    {
        public Lua      Lua;

        public MyLuaAPI()
        {
            Lua = new LuaInterface.Lua();
        }
    }
}

Now just add a public method you’d like to make available to your Lua scripts:

public void MyCoolFunction( int count )
{
    Console.WriteLine( "Got {0}!", count );
}

And change the constructor to expose the function to Lua like so:

public MyLuaAPI()
{
    Lua = new LuaInterface.Lua();
    Type self = GetType();

    Lua.NewTable( "MyLuaAPI" );
    Lua.RegisterFunction( "MyLuaAPI.CoolFunction", this, self.GetMethod( "MyCoolFunction" ) );
}

And voilà, all done! You can now instantiate your Lua API from your main program and use it:

using System;

namespace LuaInterfaceSample
{
    class Program
    {
        public static void Main()
        {
            var luaSample = new MyLuaAPI();
            luaSample.Lua.DoString( "MyLuaAPI.CoolFunction(5)" );
        }
    }
}