Easily porting Lua code to C#

is there any easy way to port Lua code to C#?

The biggest problem would probably be to port tables neatly in some dictionaries.

And to prevent any misunderstanding: no I cannot use embedded Lua in my program.

Answers


Code designed in such a highly dynamic language like Lua would need substantial refactoring to make sense in a static language like C#- the two serve fundamentally different purposes. You would have to re-write such code again from scratch, realistically, unless it used only the most basic features of any language, like basic numerical/string ops.


There's no easy way to do that.


What do you want to achieve? Convert the lua files to C# code, where you want to work with them extensively, or you just want some code that does similar things than the original code.

For the first type of conversion the answer is that it is quite hard, but not impossible. You have to parse the code and re-create the same (dynamic) functionality in C#. Frameworks, like LinFu.Reflection can help here, because they will add some dynamic functionality to CLR.

For the second type, my idea is to convert the lua bytecode to C# instead of the original code. This shouldn't be too hard, mainly because lua doesn't have much opcodes (around 30 if I remember it correctly). From these opcodes the hardest to convert are the logic and jump operators (because you don't have goto in C#), but if you keep the flow operators intact (and convert them to C# - that is more or less accomplishable), and only compile the code between, and convert the result bytecode to C# should do the job. Of course this way you'll lose a lot from the readibility of the original code, and maintaining it will be much harder.

You might also try to find a solution between these two edge cases I've written here. Some constructs can be easily ported (mainly the loops, and simple arithmetic operators), but fall back to the opcode representation for table handling.


Universal-transpiler can translate a small subset of Lua into several other languages, including C#. This is an example, written for SWI-Prolog:

:- use_module(library(transpiler)).
:- set_prolog_flag(double_quotes,chars).
:- initialization(main).

main :- 
    translate("function add(a,b) return a + b end function squared(a) return a*a end function add_exclamation_point(parameter) return parameter .. \"!\" end",'lua','c#',X),
    atom_chars(Y,X),
    writeln(Y).

This is the C# source code that it generates:

public static int add(int a,int b){
        return a+b;
}
public static int squared(int a){
        return a*a;
}
public static string add_exclamation_point(string parameter){
        return parameter+"!";
}

Need Your Help

Understanding performance of two Matrix rotation algorithms

c# algorithm

My lack of in depth understanding of the fundamentals has taken a toll on these types of problem solving challenges.