Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Lua in LA using MoonSharp
#1
Happy New Year to all. Here's a couple of Lua scripts running in LA using MoonSharp. You can get MoonSharp with NuGet. (I cloned code from here). You can return really large results with this factorial code, by the way.

First (using implicit conversion):
 
Code:
Copy      Help
// script "lua3c2.cs"
/*/ nuget lua\MoonSharp; /*/ //.
 
using MoonSharp.Interpreter;
script.setup(trayIcon: true, sleepExit: true);
//..
int myNumber;

dialog.options.defaultTitle = "MoonSharp Testing";
dialog.showInputNumber(out myNumber, "Lua Factorial Test", "Enter an integer");

dialog.show(MoonSharpFactorial2(myNumber).ToString(), "Back from Lua", title: "Lua Factorial Output");

double MoonSharpFactorial2(int aNumber)
{

    string scriptCode = @"    
        -- defines a factorial function
        function fact (n)
            if (n == 0) then
                return 1
            else
                return n*fact(n - 1)
            end
        end"
;

    Script script = new Script();

    script.DoString(scriptCode);
    // Here we get the script.Globals function by index, i.e. ["fact"]
    // This returns a System.Object. Sometimes that's not what's wanted.

    DynValue res = script.Call(script.Globals["fact"], myNumber);

    return res.Number;
}

Second, explicit conversion:
 
Code:
Copy      Help
// script "lua3c3.cs"
/*/ nuget lua\MoonSharp; /*/ //.
 
using MoonSharp.Interpreter;
script.setup(trayIcon: true, sleepExit: true);
//..
int myNumber;

dialog.options.defaultTitle = "MoonSharp Testing";
dialog.showInputNumber(out myNumber, "Lua Factorial Test", "Enter an integer");

dialog.show(MoonSharpFactorial2(myNumber).ToString(), "Back from Lua", title: "Lua Factorial Output");

double MoonSharpFactorial2(int aNumber)
{

    string scriptCode = @"    
        -- defines a factorial function
        function fact (n)
            if (n == 0) then
                return 1
            else
                return n*fact(n - 1)
            end
        end"
;

    Script script = new Script();

    script.DoString(scriptCode);
    DynValue luaFactFunction = script.Globals.Get("fact");
/*
If we are interested in avoiding conversion, we can pass a number directly instead of using the implicit conversions the Call method provides.
It’s not really needed for this but somewhere else it might be. Not all implicit conversions give the desired results.
*/

    DynValue res = script.Call(luaFactFunction, DynValue.NewNumber(aNumber));

    return res.Number;
}



Best regards,
burque505


Forum Jump:


Users browsing this thread: 2 Guest(s)