-
-
Notifications
You must be signed in to change notification settings - Fork 3
Lua State
To create a Lua state, you can use any of the constructor overloads of the Lua type.
They allow you to specify the culture, allocator, and even allow you to customize the way values are marshaled to and from Lua.
using (var lua = new Lua())
{
// code
}Lua is disposable; disposing a Lua instance closes the relevant Lua state and frees any allocated memory.
In future examples, the wiki might omit the instantiation of Lua and simply use a lua variable which you're meant to replace with your instance.
There are a bunch of Lua instance methods that allow running Lua code:
-
Execute()- executes the specified code without returning any values Lua returned -
Evaluate()- executes the specified code and returns any values Lua returned (Evaluate<T>()can be used for a single value) -
Compile()- compiles the specified code and returns it as aLuaFunction, allowing for efficient execution at a later point
using (var lua = new Lua())
{
// Set global variable x to 2
lua.Execute("x = 2");
// Get the result of x + 2
var result = lua.Evaluate<int>("return x + 2");
Console.WriteLine(result); // 4
} Compile() is more complex as it returns a LuaFunction which we have to work with manually.
// Compiles a LuaFunction that increments x by 1 and returns it
using (var function = lua.Compile("x = x + 1 return x"))
{
// Call it a few times
for (var i = 0; i < 3; i++)
{
// A Lua function can return multiple values which are all pushed onto the Lua stack
using (var results = function.Call())
{
result = results.First.GetValue<int>();
// Prints the value of x after each call, i.e. 3, 4, 5
Console.WriteLine(result);
}
}
}Lua exposes multiple ways to get and set global variables within Lua:
-
TryGetGlobal<T>()andSetGlobal<T> -
Globals- returns aLuaTablefor global variables
lua.SetGlobal("x", 42);
var x = lua.GetGlobal<int>("x");
Console.WriteLine(x); // 42Lua.Globals allows for more operations on the global variables:
var hasX = lua.Globals.ContainsKey("x");
Console.WriteLine(hasX); // True
var globalCount = lua.Globals.Count();
Console.WriteLine(globalCount); // 1Lua has many useful standard libraries. See Lua manual.
Laylua exposes these standard libraries under LuaLibraries.Standard.
E.g. LuaLibraries.Standard.Math is the mathematical functions library.
Laylua represents both these standard libraries as well as any custom libraries using the ILuaLibrary interface, which provides opening/closing capabilities for the specified Lua instance.
Opening all standard libraries:
lua.OpenStandardLibraries();Getting the value of
lua.OpenLibrary(LuaLibraries.Standard.Math);
var pi = lua.Evaluate<double>("return math.pi");
Console.WriteLine(pi); // 3.141592653589793