Skip to content

Instantly share code, notes, and snippets.

@cdhowie
Created November 15, 2013 15:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cdhowie/7486265 to your computer and use it in GitHub Desktop.
Save cdhowie/7486265 to your computer and use it in GitHub Desktop.
Proxying print() calls in Lua to C# (using Eluant)
using System;
using System.Text;
using Eluant;
class Example {
static void Main() {
using (var runtime = new LuaRuntime()) {
using (var proxy = runtime.CreateFunctionFromDelegate(new Action<LuaTable>(PrintProxy))) {
runtime.Globals["printproxy"] = proxy;
}
runtime.DoString(@"
local proxy = printproxy
printproxy = nil
print = function(...)
local itemCount = select('#', ...)
local items = { n=itemCount }
for n=1, itemCount do
items[n] = tostring(select(n, ...))
end
return proxy(items)
end
").Dispose();
runtime.DoString("print('foo')").Dispose();
Console.WriteLine("bar");
}
}
static void PrintProxy(LuaTable t) {
var sb = new StringBuilder();
using (var e = t.EnumerateArray().GetEnumerator()) {
if (e.MoveNext()) {
sb.Append(e.Current.ToString());
e.Current.Dispose();
}
while (e.MoveNext()) {
sb.Append('\t');
sb.Append(e.Current.ToString());
e.Current.Dispose();
}
}
var printedLine = sb.ToString();
// Now do what you want with the printed line, for example:
Console.WriteLine(printedLine);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment