📜 ⬆️ ⬇️

Using Lua Scripts in .NET with LuaInterface

Hi, Habrahabr!

This small post was born after I decided to find out how to run Lua scripts in conjunction with playing in C # (or in another .NET-language). using the LuaInterface library. I was impressed by the ease of this interface compared to lua.h in C ++

image
')

What you need to know


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

Start



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

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

Small educational program

LuaInterface - a library for easy integration between Lua and CLR
Lua is a very light scripting language. Here is his analysis
What are the scripts for - excerpt from my other post

Hidden text
If you have developed large projects (for example, large-scale games), have you noticed that with each new hundred lines of code, the compilation is slower?
The game creates more weapons, more dialogues, more menus, more etc.
One of the main problems arising in connection with innovations is to maintain the innumerable number of weapons and badges rather difficult task.
In a situation where a friend / boss / teammate request 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 has ever made a level map or dialog 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, head down - using scripts.

Solution to the problem

“Okay, for such cases a regular file with a description of player 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? ”
Good question. In this case, scripts come to the rescue, holding exactly the logic of the player with all the characteristics or some other part of the game.
Naturally, it’s best to keep the player’s logic in the form of a programming language code.
The first thought - to write your own interpreter of your scripting language, is thrown out of the brain in a few seconds. The logic of the player is definitely not worth such terrible costs.
Fortunately, there are special libraries of scripting languages ​​for C ++, which take a text file as input and execute it.

One such scripting language Lua will be discussed.


Now that we have a project with a connected LuaInterface, go to the code!

LuaInterface - the basics


We mainly write the .cs file
using LuaInterface; 


The main class of this library is Lua.

 Lua lua = new Lua(); 


Constant declaration


It is very easy to declare constants. It is done this way.
 lua[] = ; 

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

Anything can act as a value - a number, a string, even classes and structures (how to work with them will be further)

Registration of functions


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 along with C ++, is that you can register an object of a class and then call various functions “directly” in the script.
That is, you can do this:

C #
  class LuaDebug { //       private void Print(string message, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(message); } 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


You can execute Lua code (with all registered functions and constants) in two ways.
The first is straight from C #
 lua.DoString() 

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

Second - from file
 lua.DoFile(file) 

 lua.DoFile("script.lua") 

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

Exception Handling


To handle exceptions — errors that might pop up during script execution, you should use a LuaException err

  try { // Lua, lua, lua } catch (LuaException err) { //   } 


Calling methods from Lua


To call a method from Lua, you must run a script, retrieve the method, and execute it when necessary.
Example
 lua.DoFile("file.lua") LuaFunction func = lua["func"] as LuaFunction; // function func() {...} end func.Call(); 

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

Additional materials




image
Lua Symbols

image
Love2D - one of the most popular engines on Lua

image
Minecraft mod for Lua

image
https://bitbucket.org/Izaron/luaforhabr/src
Source

Source: https://habr.com/ru/post/197262/


All Articles