### Load and Execute Lua Scripts in C# Source: https://context7.com/nlua/keralua/llms.txt Demonstrates various methods for executing Lua code: `DoString` for immediate execution, `LoadString` followed by `PCall` for controlled execution and error handling, and `DoFile` for executing scripts from a file. ```csharp using KeraLua; using (var lua = new Lua()) { // Method 1: DoString - Load and execute in one step bool hasError = lua.DoString("print('Hello from Lua!')"); // Method 2: LoadString + PCall - For more control LuaStatus loadStatus = lua.LoadString("return 42 * 2"); if (loadStatus == LuaStatus.OK) { LuaStatus callStatus = lua.PCall(0, 1, 0); // 0 args, 1 result, no error handler if (callStatus == LuaStatus.OK) { long value = lua.ToInteger(-1); Console.WriteLine($"Computed: {value}"); // Output: Computed: 84 lua.Pop(1); } } // Method 3: DoFile - Execute a Lua file bool fileError = lua.DoFile("script.lua"); if (fileError) { string error = lua.ToString(-1); Console.WriteLine($"Error: {error}"); lua.Pop(1); } } ``` -------------------------------- ### Create and Manage Lua State with Standard Libraries Source: https://context7.com/nlua/keralua/llms.txt Instantiates a Lua state, loads standard libraries, executes a Lua string, retrieves a global variable, and cleans up the stack. The Lua state is automatically closed when exiting the 'using' block. ```csharp using KeraLua; // Create a new Lua state with standard libraries loaded using (var lua = new Lua()) { // Execute Lua code bool hasError = lua.DoString("x = 10 + 20"); if (!hasError) { // Get the result from Lua lua.GetGlobal("x"); long result = lua.ToInteger(-1); Console.WriteLine($"Result: {result}"); // Output: Result: 30 } lua.Pop(1); // Clean up the stack } // Automatically closes the Lua state ``` -------------------------------- ### Set Up Lua Debug Hooks in C# Source: https://context7.com/nlua/keralua/llms.txt Configures and uses Lua debug hooks in KeraLua to trace script execution line by line. Shows how to set, check, and disable hooks. ```csharp using KeraLua; using System; public class DebugHookExample { private static void LineHook(IntPtr luaState, IntPtr ar) { var lua = Lua.FromIntPtr(luaState); var debug = LuaDebug.FromIntPtr(ar); // Only handle line events if (debug.Event != LuaHookEvent.Line) return; // Get detailed debug info lua.GetStack(0, ar); if (lua.GetInfo("Snlu", ar)) { var updatedDebug = LuaDebug.FromIntPtr(ar); Console.WriteLine($"Line {updatedDebug.CurrentLine}: {updatedDebug.ShortSource}"); } } private static LuaHookFunction hookFunc = LineHook; public static void Main() { using (var lua = new Lua()) { // Set hook for line events lua.SetHook(hookFunc, LuaHookMask.Line, 0); // Execute script - hook will be called for each line lua.DoString(@" local x = 10 local y = 20 local z = x + y "); // Check hook properties Console.WriteLine($"Hook active: {lua.Hook != null}"); Console.WriteLine($"Hook mask: {lua.HookMask}"); // Disable hook lua.SetHook(hookFunc, LuaHookMask.Disabled, 0); } } } ``` -------------------------------- ### Control Lua Garbage Collection Source: https://context7.com/nlua/keralua/llms.txt Demonstrates how to monitor memory usage, force collection cycles, and toggle the garbage collector state. ```csharp using KeraLua; using (var lua = new Lua()) { // Create some Lua objects lua.DoString(@" local tables = {} for i = 1, 1000 do tables[i] = { data = string.rep('x', 100) } end tables = nil -- Make tables eligible for GC "); // Get current memory usage (in KB) int memoryBefore = lua.GarbageCollector(LuaGC.Count, 0); Console.WriteLine($"Memory before GC: {memoryBefore} KB"); // Force a full garbage collection cycle lua.GarbageCollector(LuaGC.Collect, 0); int memoryAfter = lua.GarbageCollector(LuaGC.Count, 0); Console.WriteLine($"Memory after GC: {memoryAfter} KB"); // Stop garbage collector lua.GarbageCollector(LuaGC.Stop, 0); // Check if GC is running int isRunning = lua.GarbageCollector(LuaGC.IsRunning, 0); Console.WriteLine($"GC running: {isRunning != 0}"); // Output: GC running: False // Restart garbage collector lua.GarbageCollector(LuaGC.Restart, 0); // Perform incremental GC step lua.GarbageCollector(LuaGC.Step, 100); } ``` -------------------------------- ### Configure UTF-8 Encoding and Binary Buffers Source: https://context7.com/nlua/keralua/llms.txt Set the Encoding property to UTF8 for Unicode support and use PushBuffer/ToBuffer for handling raw binary data. ```csharp using KeraLua; using System.Text; using (var lua = new Lua()) { // Set UTF-8 encoding for proper Unicode support lua.Encoding = Encoding.UTF8; // Push Unicode string lua.PushString("Hello, δΈ–η•Œ! 🌍"); lua.SetGlobal("greeting"); // Retrieve and verify lua.GetGlobal("greeting"); string retrieved = lua.ToString(-1); Console.WriteLine(retrieved); // Output: Hello, δΈ–η•Œ! 🌍 lua.Pop(1); // Work with binary data using buffers byte[] binaryData = new byte[] { 0x00, 0x01, 0x02, 0xFF, 0xFE }; lua.PushBuffer(binaryData); lua.SetGlobal("binary"); // Retrieve binary data lua.GetGlobal("binary"); byte[] retrievedData = lua.ToBuffer(-1); Console.WriteLine($"Binary length: {retrievedData.Length}"); // Output: Binary length: 5 lua.Pop(1); } ``` -------------------------------- ### Creating Custom Lua Libraries Source: https://context7.com/nlua/keralua/llms.txt Define libraries using LuaRegister arrays and register them with RequireF. This allows loading custom modules via the standard Lua require function. ```csharp using KeraLua; using System; public class CustomLibrary { private static int MathSquare(IntPtr state) { var lua = Lua.FromIntPtr(state); double n = lua.CheckNumber(1); lua.PushNumber(n * n); return 1; } private static int MathCube(IntPtr state) { var lua = Lua.FromIntPtr(state); double n = lua.CheckNumber(1); lua.PushNumber(n * n * n); return 1; } private static int OpenMathLib(IntPtr state) { var lua = Lua.FromIntPtr(state); // Define library functions var mathLib = new LuaRegister[] { new LuaRegister { name = "square", function = MathSquare }, new LuaRegister { name = "cube", function = MathCube }, new LuaRegister { name = null, function = null } // Sentinel }; lua.NewLib(mathLib); return 1; } // Keep references to prevent GC private static LuaFunction openMathFunc = OpenMathLib; private static LuaFunction squareFunc = MathSquare; private static LuaFunction cubeFunc = MathCube; public static void Main() { using (var lua = new Lua()) { // Register the library with require support lua.RequireF("mymath", openMathFunc, true); lua.DoString(@" -- Library is now available globally and via require print(mymath.square(5)) -- Output: 25 print(mymath.cube(3)) -- Output: 27 local m = require('mymath') print(m.square(10)) -- Output: 100 "); } } } ``` -------------------------------- ### Work with Lua Coroutines in C# Source: https://context7.com/nlua/keralua/llms.txt Illustrates using KeraLua to manage Lua coroutines, including creating, resuming, and handling yielded values. Demonstrates cooperative multitasking. ```csharp using KeraLua; using System; public class CoroutineExample { private static int YieldingFunction(IntPtr state) { var lua = Lua.FromIntPtr(state); long value = lua.CheckInteger(1); lua.PushInteger(value * 2); return lua.Yield(1); // Yield with 1 result } private static LuaFunction yieldFunc = YieldingFunction; public static void Main() { using (var lua = new Lua()) { lua.Register("process", yieldFunc); // Create coroutine lua.DoString(@" co = coroutine.create(function(n) for i = 1, n do result = process(i) coroutine.yield(result) end return 'done' end) "); // Get the coroutine lua.GetGlobal("co"); Lua thread = lua.ToThread(-1); lua.Pop(1); // Resume the coroutine multiple times thread.PushInteger(3); // Argument to coroutine int nresults; LuaStatus status = thread.Resume(lua, 1, out nresults); while (status == LuaStatus.Yield) { if (nresults > 0) { long result = thread.ToInteger(-1); Console.WriteLine($"Yielded: {result}"); thread.Pop(nresults); } status = thread.Resume(lua, 0, out nresults); } if (status == LuaStatus.OK) { string finalResult = thread.ToString(-1); Console.WriteLine($"Final: {finalResult}"); // Output: Final: done } } } } ``` -------------------------------- ### Implement Protected Calls and Error Handlers Source: https://context7.com/nlua/keralua/llms.txt Shows how to define a custom error handler function and use PCall to catch and report runtime errors in Lua scripts. ```csharp using KeraLua; using System; public class ErrorHandling { private static int ErrorHandler(IntPtr state) { var lua = Lua.FromIntPtr(state); // Get the error message string error = lua.ToString(1); // Add traceback lua.Traceback(lua, error, 1); return 1; // Return the enhanced error message } private static LuaFunction errorHandlerFunc = ErrorHandler; public static void Main() { using (var lua = new Lua()) { // Push error handler function lua.PushCFunction(errorHandlerFunc); int errorHandlerIndex = lua.GetTop(); // Load code that will cause an error LuaStatus loadStatus = lua.LoadString(@" function buggyFunction() local x = nil return x.nonexistent -- This will error end buggyFunction() "); if (loadStatus != LuaStatus.OK) { string loadError = lua.ToString(-1); Console.WriteLine($"Load error: {loadError}"); lua.Pop(1); return; } // Call with error handler LuaStatus callStatus = lua.PCall(0, 0, errorHandlerIndex); if (callStatus != LuaStatus.OK) { string runtimeError = lua.ToString(-1); Console.WriteLine($"Runtime error:\n{runtimeError}"); lua.Pop(1); } lua.Pop(1); // Pop error handler } } } ``` -------------------------------- ### Registering C# Functions in Lua Source: https://context7.com/nlua/keralua/llms.txt Expose C# methods to Lua scripts using the LuaFunction delegate. Ensure delegate references are stored to prevent garbage collection. ```csharp using KeraLua; using System; public class LuaInterop { // Define a C# function compatible with Lua's calling convention private static int Add(IntPtr luaState) { var lua = Lua.FromIntPtr(luaState); // Get arguments from stack (index 1 is first argument) long a = lua.CheckInteger(1); long b = lua.CheckInteger(2); // Push result onto stack lua.PushInteger(a + b); // Return number of results return 1; } private static int Greet(IntPtr luaState) { var lua = Lua.FromIntPtr(luaState); // Get optional string argument with default value string name = lua.OptString(1, "World"); lua.PushString($"Hello, {name}!"); return 1; } public static void Main() { // Keep delegate references to prevent garbage collection LuaFunction addFunc = Add; LuaFunction greetFunc = Greet; using (var lua = new Lua()) { // Register functions as global Lua functions lua.Register("add", addFunc); lua.Register("greet", greetFunc); // Call from Lua lua.DoString(@" result = add(10, 20) print(result) -- Output: 30 msg = greet('KeraLua') print(msg) -- Output: Hello, KeraLua! msg2 = greet() print(msg2) -- Output: Hello, World! "); } } } ``` -------------------------------- ### Lua Stack Operations and Value Type Handling in C# Source: https://context7.com/nlua/keralua/llms.txt Illustrates how to push various data types (nil, boolean, integer, number, string) onto the Lua stack, retrieve them using negative indices, check their types, and perform stack manipulations like copying, removing, popping, and clearing. ```csharp using KeraLua; using (var lua = new Lua()) { // Push different types onto the stack lua.PushNil(); // Push nil lua.PushBoolean(true); // Push boolean lua.PushInteger(42); // Push integer (long) lua.PushNumber(3.14159); // Push number (double) lua.PushString("Hello, Lua!"); // Push string // Check stack size int top = lua.GetTop(); Console.WriteLine($"Stack size: {top}"); // Output: Stack size: 5 // Read values back (negative indices count from top) string str = lua.ToString(-1); // "Hello, Lua!" double num = lua.ToNumber(-2); // 3.14159 long integer = lua.ToInteger(-3); // 42 bool boolean = lua.ToBoolean(-4); // true bool isNil = lua.IsNil(-5); // true // Type checking LuaType type = lua.Type(-1); Console.WriteLine($"Top value type: {type}"); // Output: Top value type: String string typeName = lua.TypeName(-1); Console.WriteLine($"Type name: {typeName}"); // Output: Type name: string // Stack manipulation lua.PushCopy(-3); // Copy value at index -3 to top lua.Remove(-2); // Remove value at index -2 lua.Pop(2); // Pop 2 values from stack lua.SetTop(0); // Clear the stack } ``` -------------------------------- ### Call Lua Functions from C# Source: https://context7.com/nlua/keralua/llms.txt Demonstrates calling Lua functions defined in a script from C# using KeraLua's stack-based API. Handles functions with single and multiple return values. ```csharp using KeraLua; using (var lua = new Lua()) { // Define a Lua function lua.DoString(@" function multiply(a, b) return a * b end function getMultipleValues() return 10, 20, 30 end "); // Call multiply(6, 7) lua.GetGlobal("multiply"); // Push function onto stack lua.PushInteger(6); // Push first argument lua.PushInteger(7); // Push second argument LuaStatus status = lua.PCall(2, 1, 0); // 2 args, 1 result if (status == LuaStatus.OK) { long result = lua.ToInteger(-1); Console.WriteLine($"6 * 7 = {result}"); // Output: 6 * 7 = 42 lua.Pop(1); } else { string error = lua.ToString(-1); Console.WriteLine($"Error: {error}"); lua.Pop(1); } // Call function with multiple return values lua.GetGlobal("getMultipleValues"); lua.PCall(0, 3, 0); // 0 args, 3 results long val1 = lua.ToInteger(-3); long val2 = lua.ToInteger(-2); long val3 = lua.ToInteger(-1); Console.WriteLine($"Values: {val1}, {val2}, {val3}"); // Output: Values: 10, 20, 30 lua.Pop(3); } ``` -------------------------------- ### Lua Core API Functions Source: https://github.com/nlua/keralua/blob/main/src/Names.txt Functions in the Lua core API (lua_*) provide low-level access to the Lua state, stack manipulation, and object handling. ```APIDOC ## Lua Core API Functions ### Description Functions in the Lua core API (lua_*) provide low-level access to the Lua state, stack manipulation, and object handling. ### Functions - `lua_absindex` - `lua_arith` - `lua_atpanic` - `lua_callk` - `lua_checkstack` - `lua_close` - `lua_compare` - `lua_concat` - `lua_copy` - `lua_createtable` - `lua_dump` - `lua_error` - `lua_gc` - `lua_getallocf` - `lua_getfield` - `lua_getglobal` - `lua_gethook` - `lua_gethookcount` - `lua_gethookmask` - `lua_geti` - `lua_getinfo` - `lua_getlocal` - `lua_getmetatable` - `lua_getstack` - `lua_gettable` - `lua_gettop` - `lua_getupvalue` - `lua_getuservalue` - `lua_iscfunction` - `lua_isinteger` - `lua_isnumber` - `lua_isstring` - `lua_isuserdata` - `lua_isyieldable` - `lua_len` - `lua_load` - `lua_newstate` - `lua_newthread` - `lua_newuserdata` - `lua_next` - `lua_pcallk` - `lua_pushboolean` - `lua_pushcclosure` - `lua_pushfstring` - `lua_pushinteger` - `lua_pushlightuserdata` - `lua_pushlstring` - `lua_pushnil` - `lua_pushnumber` - `lua_pushstring` - `lua_pushthread` - `lua_pushvalue` - `lua_pushvfstring` - `lua_rawequal` - `lua_rawget` - `lua_rawgeti` - `lua_rawgetp` - `lua_rawlen` - `lua_rawset` - `lua_rawseti` - `lua_rawsetp` - `lua_resume` - `lua_rotate` - `lua_setallocf` - `lua_setfield` - `lua_setglobal` - `lua_sethook` - `lua_seti` - `lua_setlocal` - `lua_setmetatable` - `lua_settable` - `lua_settop` - `lua_setupvalue` - `lua_setuservalue` - `lua_status` - `lua_stringtonumber` - `lua_toboolean` - `lua_tocfunction` - `lua_tointegerx` - `lua_tolstring` - `lua_tonumberx` - `lua_topointer` - `lua_tothread` - `lua_touserdata` - `lua_type` - `lua_typename` - `lua_upvalueid` - `lua_upvaluejoin` - `lua_version` - `lua_xmove` - `lua_yieldk` ``` -------------------------------- ### Working with Lua Tables Source: https://context7.com/nlua/keralua/llms.txt Manipulate Lua tables by pushing values onto the stack and using index-based operations. Remember to pop values from the stack to maintain balance. ```csharp using KeraLua; using (var lua = new Lua()) { // Create a new table lua.NewTable(); // Set table fields: table["name"] = "KeraLua" lua.PushString("KeraLua"); lua.SetField(-2, "name"); // Set numeric index: table[1] = 100 lua.PushInteger(100); lua.SetInteger(-2, 1); // Set as global variable lua.SetGlobal("myTable"); // Read table values back lua.GetGlobal("myTable"); // Get field by name LuaType fieldType = lua.GetField(-1, "name"); if (fieldType == LuaType.String) { string name = lua.ToString(-1); Console.WriteLine($"Name: {name}"); // Output: Name: KeraLua } lua.Pop(1); // Pop the field value // Get by numeric index lua.GetInteger(-1, 1); long value = lua.ToInteger(-1); Console.WriteLine($"Index 1: {value}"); // Output: Index 1: 100 lua.Pop(1); // Iterate over table lua.PushNil(); // First key while (lua.Next(-2)) { // Key at -2, Value at -1 string key = lua.ToString(-2); string val = lua.ToString(-1); Console.WriteLine($" {key} = {val}"); lua.Pop(1); // Pop value, keep key for next iteration } lua.Pop(1); // Pop the table } ``` -------------------------------- ### Lua Auxiliary Library Functions Source: https://github.com/nlua/keralua/blob/main/src/Names.txt Functions in the Lua auxiliary library (luaL_*) provide a higher-level API for common tasks, simplifying Lua-C integration. ```APIDOC ## Lua Auxiliary Library Functions ### Description Functions in the Lua auxiliary library (luaL_*) provide a higher-level API for common tasks, simplifying Lua-C integration. ### Functions - `luaL_addlstring` - `luaL_addstring` - `luaL_addvalue` - `luaL_argerror` - `luaL_buffinit` - `luaL_buffinitsize` - `luaL_callmeta` - `luaL_checkany` - `luaL_checkinteger` - `luaL_checklstring` - `luaL_checknumber` - `luaL_checkoption` - `luaL_checkstack` - `luaL_checktype` - `luaL_checkudata` - `luaL_checkversion_` - `luaL_error` - `luaL_execresult` - `luaL_fileresult` - `luaL_getmetafield` - `luaL_getsubtable` - `luaL_gsub` - `luaL_len` - `luaL_loadbufferx` - `luaL_loadfilex` - `luaL_loadstring` - `luaL_newmetatable` - `luaL_newstate` - `luaL_openlibs` - `luaL_optinteger` - `luaL_optlstring` - `luaL_optnumber` - `luaL_prepbuffsize` - `luaL_pushresult` - `luaL_pushresultsize` - `luaL_ref` - `luaL_requiref` - `luaL_setfunlcs` - `luaL_setmetatable` - `luaL_testudata` - `luaL_tolstring` - `luaL_traceback` - `luaL_unref` - `luaL_where` ``` -------------------------------- ### Define Custom Lua Types with Metatables in C# Source: https://context7.com/nlua/keralua/llms.txt Use metatables to define custom behavior for operations like addition and string conversion. Ensure LuaFunction delegates are stored to prevent garbage collection. ```csharp using KeraLua; using System; public class MetatableExample { private static int VectorNew(IntPtr state) { var lua = Lua.FromIntPtr(state); double x = lua.CheckNumber(1); double y = lua.CheckNumber(2); // Create userdata lua.NewTable(); lua.PushNumber(x); lua.SetField(-2, "x"); lua.PushNumber(y); lua.SetField(-2, "y"); // Set metatable lua.GetMetaTable("Vector"); lua.SetMetaTable(-2); return 1; } private static int VectorAdd(IntPtr state) { var lua = Lua.FromIntPtr(state); // Get first vector lua.GetField(1, "x"); double x1 = lua.ToNumber(-1); lua.GetField(1, "y"); double y1 = lua.ToNumber(-1); lua.Pop(2); // Get second vector lua.GetField(2, "x"); double x2 = lua.ToNumber(-1); lua.GetField(2, "y"); double y2 = lua.ToNumber(-1); lua.Pop(2); // Create result vector lua.PushCFunction(vectorNewFunc); lua.PushNumber(x1 + x2); lua.PushNumber(y1 + y2); lua.Call(2, 1); return 1; } private static int VectorToString(IntPtr state) { var lua = Lua.FromIntPtr(state); lua.GetField(1, "x"); double x = lua.ToNumber(-1); lua.GetField(1, "y"); double y = lua.ToNumber(-1); lua.Pop(2); lua.PushString($"Vector({x}, {y})"); return 1; } private static LuaFunction vectorNewFunc = VectorNew; private static LuaFunction vectorAddFunc = VectorAdd; private static LuaFunction vectorToStringFunc = VectorToString; public static void Main() { using (var lua = new Lua()) { // Create metatable for Vector type lua.NewMetaTable("Vector"); // Set __add metamethod lua.PushCFunction(vectorAddFunc); lua.SetField(-2, "__add"); // Set __tostring metamethod lua.PushCFunction(vectorToStringFunc); lua.SetField(-2, "__tostring"); lua.Pop(1); // Pop metatable // Register constructor lua.Register("Vector", vectorNewFunc); // Test in Lua lua.DoString(@" v1 = Vector(3, 4) v2 = Vector(1, 2) v3 = v1 + v2 print(v3) -- Output: Vector(4, 6) "); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.