Using C# and NLua, I am trying to convert Lua functions into bytecode so that I can store it and execute it later. I've written a small test shown below to see if I could get the basic dump and loading to work, and it seems the conversion to bytecode works but loading the generated bytecode to a function does not. It complains that the chunk is formatted wrong. When I do a similar test in pure Lua, it works, but not when I do it with C#.
C#
public void BytecodeTest(LuaFunction f){
Console.WriteLine("Starting bytecode test...");
// Convert to bytecode
string bytecode = _lua.GetFunction("string.dump").Call(f)[0] as string;
Console.WriteLine(bytecode);
// Load the generated bytecode
var loadResult = _lua.GetFunction("load").Call(bytecode);
Console.WriteLine($"Func: {loadResult[0] ?? "(null)"}");
Console.WriteLine($"Err: {loadResult[1] ?? "(null)"}");
}
Lua:
print("Running lua...")
bytecodeTest(function() print("Hello world!") end)
I have my environment set up so that the Lua bytecodeTest
points to the C# BytecodeTest
.
The output:
Running lua...
Starting bytecode test...
uaT↓?
→
xV(w@☺?@Scripts/Function.lua??☻?♂??D☻☺G☺?♦?print♦?Hello world!???????_ENV
Func: (null)
Err: binary string: bad binary format (corrupted chunk)
The bytecode looks like I would expect but I am unsure why it is unable to translate it back.