Saturday, July 3, 2010

How to: Lua + XNA

Binding Lua to XNA, may sound hard, but its not. However, you can't easily create fully scripted game logic. I guess the reason is the fact, how XNA works. Internals of XNA are calling, update(), loadContent(), Draw() etc and if you dont let it call ( ie. stay in while(scriptrunning) or something ), it messes things up.

Lua can still be used as scripting language, but its only used to load, save and such. You cant just run some script, you have to create it event based. That means, that you check in update() loop, if something needs to be done, then do it and let the XNA do the magic again, until next update() comes.


In order to get Lua working, in your XNA app, you have to do few easy steps.
Step1: Download LuaInterface
Step2: Set it as reference dll in your current project
Step3: Add some code:
Lua LuaVM = new Lua();  // Create new Lua instance// Register Function params 1= name you use IN lua, to call this method
// 2 = object target, the object, whos function you are registering
// 3 = Method you want to call LuaVM.RegisterFunction("luaName",this,GetType().GetMethod("MyFunction"));
LuaVM.DoString("LuaName()"); // Executes Lua code. This example calls MyFunction()
So, this is all you need, to get started with Lua in your own projects. What ever is your method, to get the command input from user, its fine, as long it can be changed to string and passed to DoString(); Notice thou, that when registering method, you must call it in Lua as method, so "LuaName" turns to "LuaName()". You can use parameters in there and do what ever you want. 

Other important funtion in Lua is "DoFile()". You pass a file path/name and it executes it as a Lua code. With this, you could ( for example ) load starting settings for game levels, or different kind of characters or something. I use Lua in my current project as a quake style console. I can set engine variables and call engine funtions while game is running, witch makes testing phase a lot easyer.
LuaVM.DoFile(string path); // Execute file, full of Lua stuff
You can also set references of objects to Lua. You can do it like this:
LuaVM["MyLuaObject"] = MyCsharpObject;
LuaVM.DoString("MyLuaObject.Property = 100"); // This changes MyCsharpObject Varible named Property to 100;
If that object has methods inside it, you can call em easily from Lua
LuaVM.DoString("MyLuaObject.Method()");
Simple, eh?
Thats all you need to know, in order to get started with Lua. I might add some working example project, if its needed.
-R

3 comments:

  1. Very nice, made it much easier for me to use Lua. Thanks for the tutorial and tips!

    ReplyDelete
  2. an this still be used with the LUA 2 in the site? It says it require the visual c++ runtime.

    ReplyDelete
  3. Very nice man... I'll try to create a "Lua Suport" using it in my framework. Thanks. :D

    ReplyDelete