Using Lua with C#

来源:互联网 发布:大数据分布式计算框架 编辑:程序博客网 时间:2024/05/17 03:19

Using Lua with C#
                                                                                               by Martin Echenique (http://www.gamedev.net/reference/articles/article2275.asp)

 
ADVERTISEMENT

When developing large software projects, one of the main time consuming tasks is building the program over and over. Modern day compilers and hardware try to be smarter and faster and minimize that as much as they possibly can, but being honest, we still spend quite a lot of time staring blankly at the screen between builds. To cope with that problem, we've seen an increasing trend of embedding lightweight interpreted languages that allow us to easily and quickly change pieces of code and see what happens instantly, instead of waiting for another dreadful build cycle. Two of the most common choices are Python and Lua, because the way the languages are designed and implemented makes it quite easy to embed them in other applications. Also, they provide a simpler interface for the less technically talented people to write new features without having to learn something as daunting as C++ or pester one of the programmers to code in the idea.

For this "tutorial" we're going to work with C# and the LuaInterface assembly. You can find them over at MSDN (get the .NET 1.1 framework SDK) and luaForge (version 1.3.0 at the moment). Newer versions should work just fine as soon as they come out.

Embedding Lua into C# with LuaInterface is so easy that it's almost embarrassing. The wrapper takes care of most everything and exposes a very easy to work with API. To start with it right away, we could try this:

 

Compile it and run it, you have your very own Lua console to fool around with. Not very useful as it is, but it's a start. The next thing we'd want to do is to expose some of our own functions to the Lua virtual machine. Again, LuaInterface comes to the rescue: Lua.RegisterFunction(Name, Target, Method) will do just that. The parameters needed are a string, an object instance and a MethodInfo instance for the method we want.

If you don't know what reflection is, a brief introduction is in order. If you do, just skip to the next paragraph. C# (like Java) has a very nifty feature: reflection. In a nutshell, it lets you rip apart any class, property or method at run time, without needing to know anything about it at build time. The MethodInfo instance we have to pass to the Lua VM is the reflected method taken from the object. We'll make use of it for quite a lot of things later on.

The first function we could expose to Lua would be a quit function to get rid of that horrible hack in the main loop. Our quit func could be:

 

Add System.Reflection to the list of usages and recompile. Run and now whenever you call quit() from the console, it will actually be Lua making it happen. Of course, adding functions like this is a bit awkward if you end up having hundreds of them. It also requires you to touch several parts of the program if you want to add a new function, which often leads to forgetting about some part of the process. Wouldn't it be nice if we could just flag a function somehow in it's declaration and have it automagically picked up by the Lua VM? That way, we would just have to worry about writing them. To fix this, we'll have a look at one of my favourite features of C#: Attributes.

Attributes in C# are a special class (and descendants) which exist linked with other language elements. They can be attached to class declarations, method declarations, properties, local variables or well, pretty much everything. Then, at run time, you can access them via reflection. The power of this is simply incredible, as we'll see in a moment.

First, we'll need a custom attribute class. Nothing too complicated:

 

It has a function name, a function "doc" string and an array of parameter definitions. With it, the declaration of our "quit" function would look like this:

 

We want the function to be called "quit" in Lua, and its helpful doc string just tells the user what it does. We also have a function descriptor to keep track of all added functions. So far so good, now how we do make Lua aware of those attributes to pick everything up? LuaInterface has nothing like that (yet), but we can make it fairly easily with a function. Let's call it "registerLuaFunctions":

 

Now we modify the Program class and constructor to look like this:

 

That's it. Now, as soon as you instantiate the Program class, it will register all it's functions automatically. Since the LuaVM, function hashtable and registerLuaFuncs method are all static, you can call them from wherever and add new functions to it, keeping a single centralized VM and function list.

We've being adding a lot of "Doc" stuff we have no use for yet. It's time to fix that. The following two functions make all it happen for us:

 

It's as simple as that, just write those two functions and they get inserted without you having to move a finger. They are straightforward. The first one lists all available commands (exposed from your application) and the second one gives detailed help on any command. Compile, build and try:

help()helpcmd("help")helpcmd("helpcmd")

Impressive, huh?

There is one significant improvement that can be made here and it's having functions grouped in packages for each object registering it's functions. Think of it as an exercise left to the reader. In any case, it's included in the full project here.

Discuss this article in the forums


Date this article was posted to GameDev.net: 11/7/2005
(Note that this date does not necessarily correspond to the date the article was written)

See Also:
Scripting Languages
Sweet Snippets

© 1999-2010 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
Comments? Questions? Feedback? Click here!