Skip to content

Instantly share code, notes, and snippets.

@diluculo
Forked from cdhowie/lua-printproxy.cs
Created November 18, 2015 00:40
Show Gist options
  • Save diluculo/3d6175cb6e536ccde4d5 to your computer and use it in GitHub Desktop.
Save diluculo/3d6175cb6e536ccde4d5 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