Archive for February, 2011

Embedding Lua in C# .Net – Part III

February 21, 2011

This post contains a full managed lua wrapper around the lua API, a simple script engine making life easier when communicating with lua, a sample class ‘NPCPlayer’ to integrate with lua, a sample program using the script engine and the sample class and last a basic explanation of the lua stack.

Hopefully the post will fill in the gaps from part I and II and I will provide all the working source code to illustrate lua embedding.

Source code
All files referenced in this post can be downloaded as a zip file found here.
The source code contains lots of useful comments as well.

A full managed lua wrapper
The managed wrapper is defined in its completeness in the static class ‘Lua’
This class wraps all the lua c functions and constants, and bridges the integration to the natively compiled lua.dll.

The wrapper class can be found in the zip file in the introduction of the post.

A simple Script engine – how to use the managed wrapper
The wrapper is basically just a 1-1 bridging of the full lua API and constants.
To use it you will therefore need to understand how the various lua API functions work.

Most of the functions exposed through lua API operate on the lua stack.
To make life easier in communicating with lua through the stack, I have made a simple script engine class that has methods that encapsulates the lua API calls for some of the things you’ll often have to do.

This includes:

  • Instantiating lua and managing the lua state.
  • Error logging with messages from lua interpreter
  • Registering C# methods with lua
  • Creating a lua table
  • Getting and setting table fields
  • Pushing and popping values on the lua stack
  • Running a script file

The script engine class can be found in the zip file in the introduction of the post.

Demonstration application
I have made a small console app to demonstrate the use of the scriptengine together with a sample class ‘NPCPlayer’.
The app consists of a single class ‘Program’ in a single file.

The demonstration program class and the NPCPlayer class can be found in the zip file in the introduction of the post.

The lua stack
 
The single most important thing when extending your application with lua is to understand how the lua stack works, and how exactly you use it to communicate with lua.

Stack data structure
A stack data structure is a general structure used in many different languages to solve various computing problems.
If you do not know yet what a stack structure is and how it works, you should start by looking at an explanation here.

As you can see a stack data structure is kind of a tower of data elements stacked on top off each other.
When a new data element is put on top of the stack it is called a PUSH operation.
When the top element of the stack is removed, it is called a POP operation. 

PUSH and POP always operate from the top of the stack.
The stack is also called a LIFO structure (last in first out) because of how the operations on the stack function. 

An example
As a starting example I will explain the lua API function calls used in the script engines method ‘CreateLuaTable’
The lua stack will be empty after opening lua, and the ‘CreateLuaTable’ assumes an empty stack as well.

The method looks like this and takes a single string parameter containing the name of a lua table to create in lua.

public void CreateLuaTable(string tableName)
{
            Lua.lua_getglobal(m_lua_State, tableName);

            if (IsTopNil)
            {
                //remove the nil value
                Lua.lua_pop(m_lua_State, 1);
                Lua.lua_newtable(m_lua_State);
                Lua.lua_setglobal(m_lua_State, tableName);
                //stack is empty
            }
            else
            {
                //remove the existing table from the stack
                Lua.lua_pop(m_lua_State, 1);
            }
}

Explanation
First I use lua_getglobal to check if the table already exists.
Lua_getglobal PUSHES the lua table onto the lua stack if the table did exist, else it will leave the stack with a nil value on top.

I then check if the top of the lua stack is nil, if it is the table did not exist and I will create it.
I POP the nil value off the stack with lua_pop, that takes as argument how many elements to pop.

Stack is now again empty.

I then create a new lua table with lua_newtable which PUSHES the new lua table object onto the stack

A single table element is now sitting on top of the stack.

Then I set the name of the new table by using lua_setglobal which POPS the top element from the stack (must be a table element), while associating the identifier with it.

Stack is now again empty.

If at first the table did already exists, I make sure to balance the stack again properly in the else clause, by POPPING the found table object off the stack.
Either way the stack will look exactly as it did before entering the method.

This is the easiest way to ensure proper stack use.
There can be times though when it’s fitting to leave a table object on top of the stack when performing multiple operations on the same table, instead of constantly PUSHING and POPPING it on and off the stack.

It’s critical to know exactly how each lua API function will treat the stack when it is called.
How many arguments and their types will it assume on the stack when called?
How many elements will be left on the stack when the function is done?

You will have to look this behavior up in the lua documentation, until you get familiar with it.

Conclusion 
This ends part III of Embedding Lua in C# .Net
I hope you will find the post and the code snippets useful.

Thue Tuxen


Design a site like this with WordPress.com
Get started