Interop of LUA and vice versa

On this page we will explain how to interop LUA and interop C# from LUA.

This is a real unstable API which might not work, currently.

Valid LUA Types

There are several LUA types which are allowed in Onsharp when interacting with LUA or calling remote events. Following is a list of all valid LUA types:

  • String

  • Double

  • Integer

  • Boolean

  • Table

For the table you need a wrapper class in order to use it, the Onsharp.Interop.LuaTable . It wraps the native value and offers functionality to manage this table. Please have a look in the XML documentation if you don't know how to use it. The LuaTable represents the list as well as the dictonary.

Export C# Method to LUA

Now we want to export a C# functions so we can use these functions in LUA. For that we need a function and marking the function as exportable like so:

[LuaExport("add")]
public int Add(int i1, int i2)
{
    return i1 + i2;
}

To call the C# function we need to know two things: With which name the function was exported and the plugin id of the plugin the method is in. If we know these two things we can easily call the function like this:

local result = CallOnsharp("plugin-id", "add", 10, 20)

Register Exportables

By default, any entry points as well as the plugin main class are registered for the exportables. But if you want to make a class, which is neither the plugin main class nor an entry point, can be registered manually. Therefore you just need to call either Server.RegisterExportable(new Exportables()) or Server.RegisterExportable<Exportables>() both of them can only be called from an entry point class. Please keep one thing in mind: Manually registering of exportables with the second method will only work with static exportable handling methods, and with the first one only with non-static ones.

Import LUA Function

To import LUA functions, these functions needs to be exported with AddFunctionExport. Now you can import the functions via importing the package and than calling the specified exported functions.

Importing the package is quite simple:

LuaPackage package = Server.ImportPackage("package-name");

Now you could call a function like these:

AddFunctionExport("add", function (i1, i2)
    return i1 + i2
end)

by invoke them like this:

int result = package.Invoke<int>("add", 10, 20);

Last updated