Skip to content

Instantly share code, notes, and snippets.

@juanpaexpedite
Created June 7, 2017 19:00
Show Gist options
  • Save juanpaexpedite/e49b5636187dfd4b1686fdafb6712936 to your computer and use it in GitHub Desktop.
Save juanpaexpedite/e49b5636187dfd4b1686fdafb6712936 to your computer and use it in GitHub Desktop.
LUA waiting with await
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
ScriptBox.Text =
@"
return function(j)
for i=10,20 do
paint(i*2)
wait(j);
coroutine.yield()
end
end";
}
public async void Wait(int j)
{
await Task.Delay(500);
coroutines[j].Coroutine.Resume();
}
double i = 0;
int j = 0;
Script script;
List<DynValue> coroutines = new List<DynValue>();
Random random = new Random(DateTime.Now.Millisecond);
private void AddEllipse(double diameter)
{
MainCanvas.Dispatcher.Invoke(() =>
{
var offset = i;
i += 0.1;
var color = Color.FromArgb(0xFF, (byte)random.Next(0, 128),
(byte)random.Next(0, 128), (byte)random.Next(0, 128));
var el = new Ellipse()
{
Fill = new SolidColorBrush(color),
Width = diameter,
Height = diameter,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left
};
Canvas.SetLeft(el, offset + diameter );
Canvas.SetTop(el, diameter);
MainCanvas.Children.Add(el);
});
}
int k = 0;
private async void RunScript_Click(object sender, RoutedEventArgs e)
{
k++;
ScriptsBlock.Text = $"Scripts {k}";
var scriptCode = ScriptBox.Text;
script = new Script();
try
{
script.Globals["paint"] = (Action<double>)(AddEllipse);
script.Globals["wait"] = (Action<int>)(Wait);
DynValue function = script.DoString(scriptCode);
var coroutine = script.CreateCoroutine(function);
coroutines.Add(coroutine);
coroutine.Coroutine.Resume(j);
j++;
}
catch (Exception ex)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment