Search code examples
c#luamoonsharp

Use object returned by Lua script


I have this lua script inside "Conversion.lua" file:

local conversion = {}

function conversion.mmToin( value )
    return value * 0.0393701
end

return conversion

I need to use the function mmToin in C# code, contained inside the object conversion.

If the function would not be inside the object i would have use the following code:

Script scp = new Script();
scp.DoFile(GlobalConst.PATH_TO_SCRIPT_FOLDER + "Conversion.lua");
double resultFm = scp.Call(scp.Globals["mmToin"], 1).ToObject<double>();

but i can't use the function if i put it inside an object; i've tried:

double resultFm = scp.Call(scp.Globals["conversion.mmToin"], 1).ToObject<double>();

but is not working.

How can i use mmToin function inside C# code? Thanks.


Solution

  • You need to keep a reference to the returned value of your lua script as a DynValue object, then look for the desired function in the Table property.

    DynValue dyn = scp.DoFile(GlobalConst.PATH_TO_SCRIPT_FOLDER + "Conversion.lua");
    

    and you should be then able to call your function with

    scp.Call(dyn.Table.Get("yourFunctionHere"), parameters).ToObject<double>();