Using Lua scripts in .NET with LuaInterface

    Hi, Habrahabr!

    This short post was born after I decided to learn how to run Lua scripts in conjunction with a game in C # (or in another .NET language). using the LuaInterface library. I was impressed with the ease of this interface compared to lua.h in C ++


    What you need to know

    C # at a decent level, have an understanding of the basics of programming, as well as connecting links in a project in Visual Studio


    Sources (with all dlls, of course) are posted at the end of the post.

    The first thing to do is connect LuaInterface.dll to our project. Just add the link to the .dll file. If you still do not know how to do this, then you can find manuals on the Internet. Also, luanet.dll is required for connection.

    A small educational program

    LuaInterface - a library for convenient integration between Lua and CLR
    Lua - a very easy scripting programming language. Here is his analysis.
    Why scripts are needed - excerpt from another post of mine

    Hidden text
    If you developed large projects (for example, large-scale games), have you noticed that compilation is slower with each new hundred lines of code?
    The game creates more weapons, more dialogs, more menus, more etc.
    One of the most important problems arising in connection with innovations is to support a myriad of weapons and badges rather difficult task.
    In a situation where the request of a friend / boss / partner to change the dialogue or add a new type of weapon takes too much time, you have to resort to some measures - for example, recording all this garbage in separate text files.
    Almost every game developer ever made a level map or dialogs in a separate text file and then read them. Take at least the simplest option - Olympiad tasks in computer science with an input file.

    But there is a way, a cut above - using scripts.

    Solution to the problem

    “Okay, for such cases a regular file with a description of the player’s characteristics is enough. But what to do if in a rapidly developing project almost every day you have to slightly change the logic of the main player, and, therefore, compile the project many times? ”
    A good question. In this case, scripts that support the player’s logic with all the characteristics or any other part of the game come to our aid.
    Naturally, it is most convenient to keep the player’s logic in the form of code of some programming language.
    The first thought is to write your own interpreter of your scripting language, ejected from the brain in a few seconds. The logic of the player is definitely not worth such a terrible cost.
    Fortunately, there are special scripting language libraries for C ++ that accept a text file and execute it.

    One such scripting language Lua will be discussed.

    Now that we have a project with LuaInterface connected, let's move on to the code!

    LuaInterface - the basics

    We basically write the .cs file
    using LuaInterface;

    The main class of this library is Lua.

    Lua lua = new Lua();

    Declaration of Constants

    You can very easily declare constants. It is done like this
    lua[ключ] = значение;

    lua["version"] = 0.1;
    lua["name"] = "YourName";
    lua["test"] = 200;
    lua["color"] = new Color();
    lua["my"] = this;

    The value can be anything - a number, a string, even classes and structures (more about how to work with them)

    Feature Registration

    In Lua, you can register a function from C #
    lua.RegisterFunction(название функции в Lua, this, функция);

    lua.RegisterFunction("puts", this, typeof(Program).GetMethod("Test"));

    Registration of classes and structures

    One of the most pleasant aspects of LuaInterface, which may surprise those who use Lua in conjunction with C ++, is that you can register a class object and then call different functions in the script “directly”
    That is, you can do this:

    C #
        class LuaDebug
            // Запись любого текста с указанным цветом
            private void Print(string message, ConsoleColor color)
                Console.ForegroundColor = color;
            public void Log(string message)
                Print("Log: " + message, ConsoleColor.White);
            public void Warning(string message)
                Print("Warning: " + message, ConsoleColor.Yellow);
            public void Error(string message)
                Print("Error: " + message, ConsoleColor.Red);
            public string ConsoleRead()
                return Console.ReadLine();
    // ...
    lua["Debug"] = new LuaDebug();

    And after that make a Lua script with the following content:
    str = Debug:ConsoleRead() -- считывание строки
    Debug:Log("Приложение запущено")
    Debug:Warning("Введенная строка: " .. str)
    Debug:Log("Удачного дня!")
    Debug:ConsoleRead() -- пауза

    Lua code execution

    There are two ways to execute Lua code (with all registered functions and constants)
    First - straight from C #

    lua.DoString("Debug:Log('Hello, Habr!')" + "\n" +

    The second is from the file


    (Both methods return the value of object [] - this is what the Lua script returns after execution)

    Exception Handling

    To handle exceptions - errors that may pop up during script execution, use LuaException err

                  // Lua, lua, lua
                catch (LuaException err)
                   // Обработка ошибки

    Calling Methods from Lua

    To call a method from Lua, you need to execute a script, fetch the method, and execute it when necessary.
    LuaFunction func = lua["func"] as LuaFunction; // function func() {...} end

    Also in Call (params object [] args) you can pass input parameters to the function.
    The same feint also works with values, only instead of LuaFunction we use string, int, double and so on

    Additional materials

    • For tables in LuaInterface provided class LuaTable , registered in Lua object class it as a normal variable and writing of variables in the table itself is not much different from writing variables in the Lua object
    • There is also a LuaDLL class used for “low-level” work with Lua (from lua.h). There is little sense from him, and hardly anyone uses it seriously.
                  LuaDLL.lua_createtable(luaState, 1, 1);

    Symbols Lua

    Love2D - one of the most popular engines on Lua

    Mod for Minecraft on Lua

    Source code

    Also popular now: