How to embed lua (or some other scripting language) in a C# 5.0 application

16,411

It looks like DynamicLua (GitHub, NuGet Package) has what you want:

dynamic lua = new DynamicLua.DynamicLua();
lua("print('hello world')"); // => hello world
double answer = lua("return 42"); 
Console.WriteLine(answer); // => 42
var arg = 5;
lua("function luafunction(a) return a + 1 end");
dynamic answer2 = lua.luafunction(arg);
Console.WriteLine(answer2); // => 6

Console.ReadKey();

DynamicLua is based on NLua, which can do all of this as well, but it will be more complicated.

Share:
16,411
user3251430
Author by

user3251430

Updated on June 05, 2022

Comments

  • user3251430
    user3251430 almost 2 years

    First of all, I'd like to appoligize in advance for my English.

    My question is specifically about what do I need to have in a C# application to be able to interpret a Lua script fed to said application. The Lua scripts must be able to have access to classes written in C#.

    After searching stack overflow for an answer, I think the questions that deal with this subject are outdated (I think they were asked before the Dynamic Language Runtime became a part of the .NET Framework, and I think things mat be simpler now that we have the DLR).

    Basically, what I wanted to do is this

     TypeThatExecutesLua.MethodToLoadLuaScript(script.lua);
     TypeThatExecutesLua.Execute();
    

    Now, that's supposing we don't care what script.lua returns. But there would be scenarios where the second line would be something like this:

    dynamic result = TypeThatExecutesLua.Execute();
    

    or this: dynamic result; TypeThatExecutesLua.Execute(out result);

    Similarly, if possible, I'd like to be able to pass arguments to the scripts (not sure if argument is the right word in this case, I know little about scripts), like this:

    int argument
    TypeThatExecutesLua.Execute(argument);
    

    This is probably a very basic question, but I'd really appreciate an answer that would really explain to me how to do this, instead of a link to some page, because I lack the basic knowledge to understand most of the material I came across so far by searching the web (I'm fairly good at C#, but this is out of the scope of the language itself).

    As a final note, I'd like to say that even though Lua is my target language, if the solution is similar or identical to any language, varying only in things like which dll to download and reference in your project and the interface of dll itself, I'd like to know.