Here's how to create a clean Lua integration in your C# MVVM WPF application using MoonSharp:
1. Install MoonSharp and Set Up Basic Structure
First, install the MoonSharp NuGet package, then create a service layer to handle Lua operations:
// ILuaService.cs
public interface ILuaService
{
Task<T> ExecuteScriptAsync<T>(string script);
Task<object> ExecuteScriptAsync(string script);
void RegisterObject(string name, object obj);
void RegisterFunction(string name, Func<object[], object> function);
}
// LuaService.cs
public class LuaService : ILuaService
{
private readonly Script _luaScript;
public LuaService()
{
_luaScript = new Script();
RegisterBasicFunctions();
}
public async Task<T> ExecuteScriptAsync<T>(string script)
{
return await Task.Run(() =>
{
try
{
var result = _luaScript.DoString(script);
return result.ToObject<T>();
}
catch (Exception ex)
{
throw new LuaExecutionException($"Lua execution failed: {ex.Message}", ex);
}
});
}
public async Task<object> ExecuteScriptAsync(string script)
{
return await ExecuteScriptAsync<object>(script);
}
public void RegisterObject(string name, object obj)
{
_luaScript.Globals[name] = obj;
}
public void RegisterFunction(string name, Func<object[], object> function)
{
_luaScript.Globals[name] = function;
}
private void RegisterBasicFunctions()
{
// Register common C# functions for Lua to use
_luaScript.Globals["log"] = new Action<string>(message =>
System.Diagnostics.Debug.WriteLine($"Lua: {message}"));
}
}
// Custom exception for better error handling
public class LuaExecutionException : Exception
{
public LuaExecutionException(string message) : base(message) { }
public LuaExecutionException(string message, Exception innerException) : base(message, innerException) { }
}
2. Create a ViewModel-Friendly Wrapper
Create a wrapper that integrates well with MVVM patterns:
// LuaScriptViewModel.cs
public class LuaScriptViewModel : ViewModelBase
{
private readonly ILuaService _luaService;
private string _scriptContent;
private string _output;
private bool _isExecuting;
public LuaScriptViewModel(ILuaService luaService)
{
_luaService = luaService;
ExecuteCommand = new RelayCommand(async () => await ExecuteScriptAsync(),
() => !IsExecuting && !string.IsNullOrEmpty(ScriptContent));
}
public string ScriptContent
{
get => _scriptContent;
set
{
_scriptContent = value;
OnPropertyChanged();
ExecuteCommand.RaiseCanExecuteChanged();
}
}
public string Output
{
get => _output;
set
{
_output = value;
OnPropertyChanged();
}
}
public bool IsExecuting
{
get => _isExecuting;
set
{
_isExecuting = value;
OnPropertyChanged();
ExecuteCommand.RaiseCanExecuteChanged();
}
}
public RelayCommand ExecuteCommand { get; }
private async Task ExecuteScriptAsync()
{
IsExecuting = true;
try
{
var result = await _luaService.ExecuteScriptAsync(ScriptContent);
Output = result?.ToString() ?? "null";
}
catch (LuaExecutionException ex)
{
Output = $"Error: {ex.Message}";
}
finally
{
IsExecuting = false;
}
}
}
3. Expose C# Objects to Lua Safely
Create a facade pattern to control what Lua can access:
// LuaApplicationFacade.cs - What you expose to Lua scripts
public class LuaApplicationFacade
{
private readonly IDataService _dataService;
private readonly INotificationService _notificationService;
public LuaApplicationFacade(IDataService dataService, INotificationService notificationService)
{
_dataService = dataService;
_notificationService = notificationService;
}
[MoonSharpVisible] // Only expose what you want
public void ShowMessage(string message)
{
_notificationService.ShowInfo(message);
}
[MoonSharpVisible]
public object GetData(string key)
{
return _dataService.GetValue(key);
}
[MoonSharpVisible]
public void SetData(string key, object value)
{
_dataService.SetValue(key, value);
}
}
4. Enhanced LuaService with Application Context
public class EnhancedLuaService : ILuaService
{
private readonly Script _luaScript;
private readonly LuaApplicationFacade _appFacade;
public EnhancedLuaService(LuaApplicationFacade appFacade)
{
_appFacade = appFacade;
_luaScript = new Script();
// Configure MoonSharp
UserData.RegisterType<LuaApplicationFacade>();
// Expose your application facade
_luaScript.Globals["app"] = _appFacade;
RegisterStandardLibraries();
}
private void RegisterStandardLibraries()
{
// Only register safe standard libraries
_luaScript.Options.CheckThreadAccess = false;
// Register math functions
_luaScript.Globals["math"] = new
{
sqrt = new Func<double, double>(Math.Sqrt),
pow = new Func<double, double, double>(Math.Pow),
sin = new Func<double, double>(Math.Sin),
cos = new Func<double, double>(Math.Cos)
};
}
// Rest of implementation...
}
5. Script Management System
Create a system to manage and organize Lua scripts:
// LuaScriptManager.cs
public class LuaScriptManager : ViewModelBase
{
private readonly ILuaService _luaService;
private readonly IFileService _fileService;
private ObservableCollection<LuaScript> _scripts;
private LuaScript _selectedScript;
public LuaScriptManager(ILuaService luaService, IFileService fileService)
{
_luaService = luaService;
_fileService = fileService;
_scripts = new ObservableCollection<LuaScript>();
LoadScriptsCommand = new RelayCommand(async () => await LoadScriptsAsync());
SaveScriptCommand = new RelayCommand(async () => await SaveScriptAsync(),
() => SelectedScript != null);
RunScriptCommand = new RelayCommand(async () => await RunScriptAsync(),
() => SelectedScript != null);
}
public ObservableCollection<LuaScript> Scripts
{
get => _scripts;
set
{
_scripts = value;
OnPropertyChanged();
}
}
public LuaScript SelectedScript
{
get => _selectedScript;
set
{
_selectedScript = value;
OnPropertyChanged();
SaveScriptCommand.RaiseCanExecuteChanged();
RunScriptCommand.RaiseCanExecuteChanged();
}
}
public RelayCommand LoadScriptsCommand { get; }
public RelayCommand SaveScriptCommand { get; }
public RelayCommand RunScriptCommand { get; }
private async Task RunScriptAsync()
{
if (SelectedScript == null) return;
try
{
var result = await _luaService.ExecuteScriptAsync(SelectedScript.Content);
SelectedScript.LastResult = result?.ToString();
SelectedScript.LastExecuted = DateTime.Now;
}
catch (Exception ex)
{
SelectedScript.LastResult = $"Error: {ex.Message}";
}
}
}
// LuaScript.cs - Model for script data
public class LuaScript : ViewModelBase
{
private string _name;
private string _content;
private string _lastResult;
private DateTime? _lastExecuted;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged();
}
}
public string Content
{
get => _content;
set
{
_content = value;
OnPropertyChanged();
}
}
public string LastResult
{
get => _lastResult;
set
{
_lastResult = value;
OnPropertyChanged();
}
}
public DateTime? LastExecuted
{
get => _lastExecuted;
set
{
_lastExecuted = value;
OnPropertyChanged();
}
}
}
6. Dependency Injection Setup
Register your services in your DI container:
// In your App.xaml.cs or DI configuration
services.AddSingleton<ILuaService, EnhancedLuaService>();
services.AddTransient<LuaApplicationFacade>();
services.AddTransient<LuaScriptViewModel>();
services.AddTransient<LuaScriptManager>();
7. Usage Example in XAML
<UserControl x:Class="YourApp.Views.LuaScriptView">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox Grid.Row="0"
Text="{Binding ScriptContent, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="True"
FontFamily="Consolas"/>
<Button Grid.Row="1"
Command="{Binding ExecuteCommand}"
Content="Execute Script"
IsEnabled="{Binding IsExecuting, Converter={StaticResource InverseBooleanConverter}}"/>
<ScrollViewer Grid.Row="2">
<TextBlock Text="{Binding Output}"
FontFamily="Consolas"
Background="Black"
Foreground="Green"/>
</ScrollViewer>
</Grid>
</UserControl>
This setup provides a clean, MVVM-compliant integration with proper separation of concerns, error handling, and security considerations. The Lua scripts run in a controlled environment with limited access to your application's functionality.