LuaInterface

While having a beer with an old friend yesterday, we started discussing the use of scripting languages in applications. Having seen a number of .net applications with embedded Lua scripting engines, I suggested that he look at LuaInterface, with the disclaimer that I hadn’t used it much myself.

Having nothing better to do this afternoon, I decided to download the whole thing again (the last version I’d downloaded had languishing in my download folder for about 10 months, and was probably out of date, if I could find it in the first place) and have a go at it. Attached are the results of my messing around. It’s by no means a best practice guide – or even a good practice guide, for that matter – but it looks like it’s working.

Getting lua to work in .net is simple enough; add a reference to luainterface.dll and put the luanet and lua51 dlls somewhere accessible to your application. In my case I added them as content in my VS project, and set the copy mode to “Copy Always”.

To initialise a scripting context, create a new instance of LuaInterface.Lua, which is as simple as:

LuaInterface.Lua m_ScriptingEngine = new LuaInterface.Lua();

To expose a .net object to the scripting engine, use the engine’s indexer, like so:

ScriptingEngine["winform"] = this;

this allows the scripts to access the object and it’s properties as follows:

winform.Text = “Title Goes Here”

The lua syntax to call a method from a script is <object>:<method>(parameters) -

winform:Close()

The scripts can also access and create .net types, such as forms and buttons. The assemblies and the types must be registered first, as follows:

– Reference the .Net assemblies.
luanet.load_assembly(“System.Windows.Forms”)

– Import the specific types.
Menu = luanet.import_type(“System.Windows.Forms.MainMenu”)
MenuItem = luanet.import_type(“System.Windows.Forms.MenuItem”)

I’ve uploaded my example project. Nothing groundbreaking, but it may be useful for anyone who’s still testing the waters on this.

Further reference

Lua Reference Manual
Lua Home

6 thoughts on “LuaInterface

  1. Thank you for your comments :)

    To call Lua functions from your C# application, you will need to get the function from the instance of the scripting engine and use its Call method i.e.

    Lua instance = new Lua();


    LuaFunction myFunction = instance.GetFunction(“myLuaFunction”);
    myFunction.Call();

    Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>