jvtrudel
jvtrudel

Reputation: 1345

Convert mathematica functions to lua

I want to read files written using the Mathematica function 'Save'. Inside, their are expressions that I would like to translate in lua.

For example: mathematica -> lua

foo[bar_]:= a*bar + b     ->    function foo(bar) return a*bar + b end   
foo[bar_]= a*bar + b      ->    foo[bar] = a*bar + b
foo = N[bar]              ->    foo = bar
Pi or \[Pi]  or           ->    math.pi
-7.809692029744407*^-8    ->    -7.809692029744407e-8
2.7067*^-8 + 2.268*^-8*I  ->    2.7067e-8 + 2.268e-8*math.i

This is not necessarily a hard problem, I just have to learn the lua regular expressions. But their is a lot of cases (not mentioned above) to take into account and I do not want to "reinvent the wheel". Maybe I should, you would say...

But anyways, is there a lua library or a project devoted to that?

Upvotes: 2

Views: 310

Answers (2)

Anderson Green
Anderson Green

Reputation: 31850

I wrote a translator that can convert a subset of Mathematica into Lua and several other languages.

It's still a work-in-progress, but it can already translate simple Mathematica functions like this one:

doSomething[a_,b_] :=
    If[a<3,
        (a =  a + 1;a),a-1]

This is the output for this function in Lua:

function doSomething(a,b) 
    if a<3 then 
        a=a+1 
        return a 
    else 
        return a-1
    end
end

I am also planning to write a translator that will convert a subset of Mathematica into symmath-lua notation.

Upvotes: 1

ogerard
ogerard

Reputation: 735

I don't know of something already done in that direction but I would recommend you consider building a Mathematica to Lua translator in Mathematica, something like a "LuaForm" saving its output to a text file. It would use existing bricks such as FortranForm / CForm to convert basic expressions (such as numbers and algebraic combinations of variables) and you could add new rules as you make use of additional Mathematica features.

CForm /@ {Pi, \[Pi], a b+3x, -7.809692029744407*^-8, 2.7067*^-8 + 2.268*^-8*I}

{Pi,Pi,a*b + 3*x,-7.809692029744407e-8,Complex(2.7067e-8,2.268e-8)}

I have done similar code in the past (for other target languages) with satisfactory results.

Upvotes: 4

Related Questions